How to fix Uncaught TypeError: cannot read properties of null (Reading 'clone')

https://playcanvas.com/editor/scene/1962856

Im trying to make a gun shoot a projectile but this error keeps popping up.
It’s in line 162 in movement.js
How do I fix it?

Hi @ssgrts and welcome!

Normally the error means that you try to clone an entity that doesn’t exist. In this case the entity you try to clone exist, so on my mobile I can’t see what’s wrong.

Do you still get the error?

Yes

Hi @ssgrts,

I took a look at your project, and can point you in the right direction. The problem is that your Bullet (in the hierarchy) is enabled at app start. This means that your first bullet is cloned effectively and fired, but because you teleport it to the same spot as the original bullet, the collision logic you have destroys the original bullet (and the 2nd one you teleport there too, really).

Because of this, the 2nd time you fire, there is no longer a bullet in the hierarchy to clone for the script. The immediate fix, on my fork, was simple to disable the bullet in the editor. Luckily, your script is already enabling it when firing.

That being said, I see that your bullet is a template. You don’t even need to have it as a part of the initial scene and could instead simply instantiate the template. This will keep your scene clean and give you greater control of the entities that are spawned.

For more information about templates, check out this user-manual page explaining them:

or this forum post:

I hope this is helpful.

3 Likes

is it possible for you to show me what you did because I cant seem to get it to work

Here is the link to my fork:

https://playcanvas.com/editor/scene/1963770

You should be able to see that the only action I took was disabling the Bullet in the editor.

image

Ok I see now. Thank you for your help

1 Like