AI script bug help needed. Errors showing up that don't make sense

Hello, I have a script that doesn’t work and I don’t know why.

Wow, are you programming on iPad!? That’s impressive!

Anyway, the error is saying “You tried to call getPosition() for player, but actually player is null and I can’t do that”.

Why player is null? It’s because somehow app.root.findByName(‘UFO’) returned null rather than the desired entity object.
Why app.root.findByName(‘UFO’) returned null? It’s because you put app.root.findByName(‘UFO’) in a wrong place.

In your code, app.root.findByName(‘UFO’) is called BEFORE PlayCanvas Engine creates/initializes bunch of entities in your program. Since there is not UFO object created yet, app.root.findByName(‘UFO’) returns null.

If you call app.root.findByName(‘UFO’) in initialize(), it will be called AFTER PlayCanvas creates/initializes entities. Then app.root.findByName(‘UFO’) will return an UFO entity object and you will be able to call getPosition() without error.

I recommend you to read this article. This explains the order of function call very well.

So the fix would look like this
initialize: function() {
this.player = app.root.findByName(‘UFO’);

update: function(dt) {
var pos = this.player.getPosition();

1 Like

I’m glad I can impress you. I’m not exactly sure what to say. Anyway, I fixed that part but I’m still getting the error.

That’s unfortunate. But I think the cause is somehow “player” is null. Potentially…

  1. You did “var pos = player.getPosition();” rather than “var pos = this.player.getPosition();” in line 18.
  2. The use of “app.root.findByName(‘UFO’);” is wrong.

Please check your code carefully! But I recommend you to use PC since PC browser has debugger in it unlike iPad browser. Good luck!