Don_Huan
Don_Huan

Reputation: 85

Remove or Delete spawning objects from the List

I made a script that spawning unlimited moving objects with LIST from positions .I want to delete the objects that collides for example with boundary.I tried to delete them applying destroy script to the object , but the console output was ..."has been destroyed but you are still trying to access it" or "use DestroyImmediate".How to destroy them?Any suggestions?

Spawning Code:

public  List<GameObject> respawn = new List<GameObject> ();
public Vector3[] positions=new Vector3[5];  
public GameObject barrier;
public BarrierMoving barrierMoving;
public bool isMoving=true;
public int lastRandom = 0;

float speed=60f;

void Start ()
{
    barrierMoving = GameObject.FindObjectOfType<BarrierMoving> ();
    InvokeRepeating ("SpawnBarrier",1f,speed*Time.deltaTime);
}

public void Update ()
{
    if(isMoving)
    {
        foreach(GameObject stop in respawn)
        {
            stop.transform.Translate (0f,0f,-0.4f);
        }
    }
}

// Spawning Function
void SpawnBarrier()
{
    for(int i=0;i<=5;i++)
    {
        respawn.Add (Instantiate (barrier, positions [i], Quaternion.identity)as GameObject);
    }
}

Destroy Script:

RespawnBarriers respawnBarriers;

void Start ()
{
    respawnBarriers = GameObject.FindObjectOfType<RespawnBarriers> ();
}

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.CompareTag("Destroy"))
    {
        Destroy (respawnBarriers.barrier);
    }
}

Upvotes: 0

Views: 228

Answers (1)

Immorality
Immorality

Reputation: 2174

You reference your list in the update method of your spawning code. When you destroy your object in your destroy script, the reference of it in your respawn list is lost and generates your error.

You should remove the reference from the respawn list before destroying the object. I would recommend making a static reference to your spawn script for easy access, if you only have one instance of it.

Upvotes: 1

Related Questions