Why not can't spawn the object?

It always said “The object of type ‘GameObject’ has been destroyed but you are still trying to access it.”

How can I fix that :frowning:

var broken1 : GameObject;
var broken1_sPoint : Transform;

function OnCollisionEnter(collision : Collision){
  if(collision.gameObject.tag=="button1"){
  
     Destroy(broken1);
     yield WaitForSeconds(2);
     var broken1 = Instantiate(broken1, GameObject.Find("broken1_sPoint").transform.position,Quaternion.Euler(0, 0, 0)); 

  }

1 Answer

1

You are destroying the object 2 lines before you instantiate it.

     Destroy(broken1); // You are destroying here
     yield WaitForSeconds(2);
     var broken1 = Instantiate(broken1, GameObject.Find("broken1_sPoint").transform.position,Quaternion.Euler(0, 0, 0)); //And creating here

So what you can do is store it in a global variable. And every time you enter the collider create a new one.

private GameObject storedObject;


    function OnCollisionEnter(collision : Collision){
      if(collision.gameObject.tag=="button1"){
    
    if(storedObject != null)
    {
         Destroy(storedObject);
         storedObject = new GameObject();
    }


         storedObject = Instantiate(broken1,    GameObject.Find("broken1_sPoint").transform.position,Quaternion.Euler(0, 0, 0)); 
     
      }