mardi 26 novembre 2019

Only one instance of an object at a time

I'm creating a simple 2D game in Unity. When you press the space bar the game will shoot a ball, and when you press space bar again the ball should "reset". Only one ball should be on the screen at any given time. Here is the conditional logic that I now use to check if a certain GameObject is in the scene. I know that Destroy(cannonBall); turns it into a null, but I can't seem to figure out how I should do this logic differently. Now I get the error that I'm trying to access a deleted object after the conditional logic removes the first ball. (I'm quite new to Unity, and I haven't posted my entire script.)

if (Input.GetKeyDown(KeyCode.Space) && GameObject.Find("Projectile(Clone)")) {
    Destroy(cannonBall);
}
else if (Input.GetKeyDown(KeyCode.Space) && GameObject.Find("Projectile(Clone)") == null )
{
    cannonBall = Instantiate(cannonBall, barell.position, barell.rotation);
    cannonBall.GetComponent<Rigidbody2D>().AddForce(degree * ballVelocity);
}

Aucun commentaire:

Enregistrer un commentaire