- Home /
How do I restrict game to only instantiate 1 instance of object?
I'm building a space shooter (i know, but it's my first ever game). I have an asteroid in my game that when it is hit by a bullet and explodes, it leaves behind a shield 'token' that the player can collect and it activates their shield. The problem is, my ship has two guns, which fire simultaneously, so if the player hits the asteroid with both bullets, 2 instances of the shield token are instantiated.
Is there any way to restrict this so that only one shield 'token' is instantiated? I tried a boolean flag with an IF statement but it didn't seem to work, I also tried turning the bullet collider off once the bullet hits the asteroid, anyone have any ideas?
my code:
//script for bullet
var explosion :Transform; var shieldBut :Transform;
if(other.gameObject.tag == "asteroidShield") { //create impact explosion Instantiate(explosion, transform.position, transform.rotation); audio.PlayClipAtPoint(fxExplosion,transform.position); Destroy(gameObject); //instantiate shield 'token' Instantiate(shieldBut, transform.position, transform.rotation); }
Any help would be greatly appreciated.
Don't know why this question hasn't been approved by the mods yet, but I found a solution: I simply instantiated the shield token from the asteroid, ins$$anonymous$$d of instantiating it from the bullet.
Answer by riggerman · Aug 10, 2012 at 11:55 AM
Yeah, actually you'll see further on that it's better to have the instancing of your "powerups" centralized in a static class or even into a separate prefab. That way it is easier and cleaner to keep track of what has been instantiated. (think farther, in counts for achievements)
Then, no matter how much bullets hit the asteroid, the centralized spawner would filter and let only one shield token be instantiated. :)
Your answer
Follow this Question
Related Questions
How to instantiate object onto other object from script 1 Answer
Instantiate a COMPLETELY Unique Instance of an Object 1 Answer
NullReference Exception when adding a class 2 Answers
Associate objects to a prefab 1 Answer
Random array issue C# 2 Answers