Hi guys I’m coding a small game in which I want the user to be able to click an emergency button to kill all enemies on screen
var destroyus : String ;
//var thatwasclicked : GameObject;
function OnMouseOver ()
{
if (Input.GetMouseButtonDown(0))
{
//find.GameObject.tag(destroyus) "
{ Destroy gameobject.tag(destroyus);
print("objects with tag should be gone ");
}
}
This is the code I have thus far, and its to be applied to the game object the user clicks to clear the screen . Any hints on why it wont compile would be greatly appreciated
Use kevork’s code. Yours has an infinite loop, since i-- is outside the loop. It won’t work anyway even if fixed, since it will just destroy the first object it finds with the “enemy” tag 15 times (which isn’t any better than destroying it once ); it won’t destroy 15 different enemies. (That’s kind of an odd way to loop anyway; typically you’d use “for (var i = 0; i < 15; i++)”. You don’t need or want to declare i outside the function; get rid of that. Always use local variables where possible.)
var i :int;
var numbergone : float = 3;
var destroyus : String;
function OnMouseOver ()
{
if (Input.GetMouseButtonDown(0))
{
while(i<numbergone)
{
i++;
yield WaitForSeconds(0.0001);
Destroy(gameObject.FindWithTag(destroyus));
}
}
}
For some reason it ignores the number gone var , but anyway It does what i need—
Need to fix this, it will stop at the numbers gone var total, but as I never resets it feels like a one use button…
var i :int;
var numbergone : float = 3;
var destroyus : String;
function OnMouseOver ()
{
if (Input.GetMouseButtonDown(0))
{
while(i<numbergone)
{
i++;
yield WaitForSeconds(0.0001);
Destroy(gameObject.FindWithTag(destroyus));
}
i=0;}
}
“yield WaitForSeconds(0.0001)” won’t actually yield for .0001 seconds. The least amount of time it can yield for is one frame, which will probably be around .01 - .02 seconds. So you might as well just use yield, which waits a frame. However, you should really really use kevork’s code, and not do it using yield. Even though it “works” in this situation, the code you posted is flawed in a number of ways and can easily break.
I couldn’t get kevork’s code to compile .
This is at most a temporary work around until I find a way to destroy all the game objects with said tag at once .
Might I suggest PoolManager? Especially if you’re planning on Destroy/Instantiating a lot of objects in your game. Be easier then to destroy (or despawn ) all enemies in a pool group.