- Home /
Test for a game object's existence.
Is there a keyword I could use to test for an object's existence? I want to make it so that only one bullet can be fired at a time.
By "only one bullet can be fired at a time", do you mean can only be fired at certain intervals? Also, to test for the existence of an object, you could simply check whether it is null through if (gameObjectName), however that will be a reasonably inefficient way of doing things in this case.
Answer by by0log1c · Apr 10, 2012 at 04:07 PM
GameObject implements the boolean operator which means you can just do:
if(GameObject.Find("ObjectName"))
{
DoSomething();
}
@$$anonymous$$leptomaniac's alertness has increased by 0.1%. It is now 95.7%.
Answer by Kryptos · Apr 10, 2012 at 04:11 PM
You can use GameObject.Find or Object.FindObjectOfType, but these methods are quite expensive. And this way you will have to name each bulet with a different name or use a different class (type).
The best way is to keep a reference to your bullet once it is fired, and set this reference to null when the bullet is destroyed (or after a timeout). This way each gun can only fire one bullet at a time, but several guns can fire simultaneously:
public class Gun : MonoBehaviour
{
public GameObject bullet;
public void Fire()
{
if(this.bullet == null)
{
// code that shoot your bullet...
this.bullet = mybullet; // assuming your instantiated bullet is mybullet
}
}
public void BulletDestroyed()
{
this.bullet = null;
}
}
Answer by MetalMario · Apr 10, 2012 at 08:35 PM
Thank you everyone for the answers.
By firing one at a time, I meant when it disappears for any reason, you should be able to fire again (i.e., when it leaves the screen or hits an enemy.)
I'll give these a try next time I work on it. For anyone wondering, this is my first game, it's a simple project for my college Intro to Gaming class. Thanks again for the quick responses. :)