How to Instantiate only once?

Hello i am making a Snake game. i have managed to Instantiate a "apple" once the game is started. But after "picking" the apple up i dont know how to Instantiate ONLY one apple at a random location.

Can you awesome people possibly help me? :)

First you need a reference to the apple in a script that is not attached to the apple. Perhaps a script attached to the snake would do the trick.

var apple : GameObject;

You can assign the apple variable using the Inspector.

When the apple is picked up, simply deactivate it in your script:


Then when you want to spawn it again, re-activate it and set its location:

apple.transform.position = GetRandomPosition();

If there's no delay between picking it up and respawning, you could just skip the deactivating/activating and set its position to a new value each time it's eaten.

  • First you should have a prefab for your apple.
  • Once this is done, your script must have a link to your prefab.
  • Then it's a simple matter of instantiating the apple at a given time.

See this example code:

// This is your prefab link. 
// You set it typically in the editor inspector.
public GameObject applePrefab;

// Of course you need to call this method from
// an appropriate place like OnTriggerEnter or OnCollisionEnter
void SpawnApple()
    GameObject appleClone = Instantiate(applePrefab) as GameObject;
    appleClone.position = GetRandomPosition(); 
    // You have to decide what a proper random position is, so
    // you must write this method.

See also OnTriggerEnter, OnCollisionEnter.

The reason I tell you about prefabs is that I think it is a common mistake to attempt to use a "live" game object as your prefab. That reference would then become invalid upon destruction and can't be used to instantiate clones properly. Also, beware of trying to clone live game objects either way because they can become hard to manage.

The main problem you seem to have though, is probably that you're checking a reference to see if it exists or not. Once the apple is picked up, the reference becomes invalid (null) and I assume you try to create a new apple. If this is the case, make sure to update that reference directly after instantiating the new prefab or you might run into a case where your script thinks there is no apple out there, while there actually is. I would personally use the events for something like this.