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.
GameObject implements the boolean operator which means you can just do:
if(GameObject.Find("ObjectName"))
{
DoSomething();
}
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;
}
}
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.