[2D] Instantiate() duplicates former instances
Hi!
I'm trying to spawn projectiles using the following code:
projectileInstance = Instantiate(projectile, LaunchUnit.position + spacer, player.transform.rotation) as Rigidbody2D;
...where
projectile
is a Rigidbody2D I stored outside the scene as the original,
LaunchUnit.position + spacer
is a point in front of the char where projectiles are created,
player.transform.rotation
makes sure the projectile is pointing in the right direction.
Now this is giving me some bad, bad headache, because of the following:
Everything is cool as long as I fire slowly. The original is being cloned, flies to its fate, and gets destroyed as it hits an outside collider responsible for disposing objects that fly off screen.
Now stuff gets weird: If I fire too rapidly or a formerly created instance isn't destroyed yet, Instantiate() not only creates an instance from the original, but also from every single instance of "projectile" that's already there.
Why does it do that? Am I missing something? Is my instantiation code wrong? Does the original GameObject have faulty properties? I have no clue...
Any Ideas?
PS: Ignore the crappy gfx and the buggy projectile rotation, all still WIP. :)
~ Incendor
Answer by incendor · Mar 02, 2018 at 08:56 AM
OK I think I have it figured out.
Because the Script is attached to the original projectile, each copy of the projectile also executes the script whenever Fire1 is pressed.
That's why it spawns a projectile for every single existing one.
I'll try fixing this tonight and mark this up as an answer if it works.
Your answer
![](https://koobas.hobune.stream/wayback/20220612153741im_/https://answers.unity.com/themes/thub/images/avi.jpg)