Unity3D spawning 2d objects at fixed locations

0 down vote favorite

I have an object that when clicked it is destroyed and spawns randomly somewhere else on a timer. I’m trying to make it so instead of random spots it shows up at fixed locations.

I also want them to randomly spawn at those fixed locations on a timed interval, one at a time.(so if it appears in one location for lets say 5 seconds, it will be destroyed and the next one will appear in a different location.)

I attempted to do fixed spawn locations, but the void spawner doesn’t want to work.

I get a “The object of type “GameObject” has been destroyed but you are still trying to access it”.

I can fix this by commenting out the On_TouchStart destroy line, but I need it.

Here is my code:

using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour {

    public float AppearTime = 0f;
    public Transform[] teleport;
    public GameObject[] prefab;

    void Spawner(){ 
        int tele_num = Random.Range(0,5);
        int prefab_num = Random.Range(0,3);
        if (prefab !=null){
        Instantiate(prefab[prefab_num],

teleport[tele_num].position,
teleport[tele_num].rotation );
}
}

    void StartTime()
    {
        StartCoroutine(DoTime());

    }

    void OnEnable(){
        EasyTouch.On_TouchStart += On_TouchStart;
    }

    IEnumerator DoTime()
    {
        yield return new WaitForSeconds(AppearTime);
        Spawner();

    }

    void On_TouchStart (Gesture gesture){

        if (gesture.pickObject != null){
            Destroy(gesture.pickObject);
            StartTime();
        }
    }

If anyone could lead me on the right track I’d appreciate it.

Thanks.

Hi

Im not 100% sure but one thing it could be is that you are destroying the reference inside of your public GameObject prefab

Can you check that there are no nulls in your array when you destroy the object? Do this and let me know (commented line is pesudo code)

 void On_TouchStart (Gesture gesture){
 
        if (gesture.pickObject != null){
            Destroy(gesture.pickObject);
            //for each object in prefab if null debug.log(null found!)
            StartTime();
        }
    }

Update: Ok here’s what I want you to check do this in your spawner method:

void Spawner(){ 
         int tele_num = Random.Range(0,5);
         int prefab_num = Random.Range(0,3);
         if(prefab[prefab_num] == null) Debug.Log("It is NULL");
         if (prefab !=null)
         {
              Instantiate(prefab[prefab_num],teleport[tele_num].position,teleport[tele_num].rotation );  
         } 
       }

Let me know what comes up.

If it is null, its one of two things:
Either your array index are going out of bounds, or you deleted the object in the array when you did your GameObject.destroy().