InvokeRepeating problem - apple spawn in snake 2D game

Hello!
I want to make food spawner but have problem with this script because it spawn food all time every 4 seconds.
I want to have only one prefab in scene and when I destroy it then want to have another one.

using UnityEngine;
using System.Collections;

public class AppleSpawner : MonoBehaviour {

    // Food Prefab
    public GameObject foodPrefab;
   
    // Borders
    public Transform borderTop;
    public Transform borderBottom;
    public Transform borderLeft;
    public Transform borderRight;
   
    // Use this for initialization
    void Start () {
        // Spawn food every 4 seconds, starting in 3
       
            InvokeRepeating ("Spawn", 4, 3);
       

    }

    void Update()
    {

    }
   
    // Spawn one piece of food
    void Spawn() {
        // x position between left & right border
        int x = (int)Random.Range(borderLeft.position.x+1f,
                                  borderRight.position.x-1f);
       
        // y position between top & bottom border
        int y = (int)Random.Range(borderBottom.position.y+0.5f,
                                  borderTop.position.y-0.5f);
       
        // Instantiate the food at (x, y)
        Instantiate(foodPrefab,
                    new Vector2(x, y),
                    Quaternion.identity); // default rotation
    }

I tried already with this:

if (GameObject.Find ("apple(Clone)") == null) {
            InvokeRepeating ("Spawn", 1, 1);
  }

but not working ;/
Thanks for help!

You would have to add the null checker part of the scrip[t to your Invoke Method. Something like this:

  void Spawn() {
        // x position between left & right border
        int x = (int)Random.Range(borderLeft.position.x+1f,
                                  borderRight.position.x-1f);
  
        // y position between top & bottom border
        int y = (int)Random.Range(borderBottom.position.y+0.5f,
                                  borderTop.position.y-0.5f);
  
        // Instantiate the food at (x, y)
if (GameObject.Find ("apple(Clone)") == null) {
        Instantiate(foodPrefab,
                    new Vector2(x, y),
                    Quaternion.identity); // default rotation
         }
    }

This new code should work!

1 Like

Thank you so much! :smile:

1 Like

You should avoid using destroy and practice with recycling objects. Just turn the object off when it is picked up and check every x seconds if it is activated or not. If not, you simply turn it on again.

Yeah I was going to mention this to but I figured I might as well solve your original problem first. This is a good idea though, and it also saves on a lot of game memory because it doesn’t have to run as many commands.