TheEvil_potato
TheEvil_potato

Reputation: 33

Respawn Prefab After 5 Second's Error?

So this is my script and I get the error (Transform) 'MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Transform.get_position () (at C:/BuildAgent/work/aeedb04a1292f85a/artifacts/EditorGenerated/UnityEngineTransfo‌​rm.cs:28)' –

#pragma strict

var objectToSpawn : GameObject;

function Update () {
    if (Input.GetMouseButtonDown(0)) {
    var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        var hit : RaycastHit;
        if (Physics.Raycast (ray, hit)) {
           if (hit.collider.tag == "destroyable") {
               var oldTransform = hit.collider.gameObject.transform;
               Destroy(hit.collider.gameObject);
               StartCoroutine(SpawnAfter5Seconds(oldTransform));
            }
         }
    }
}

function SpawnAfter5Seconds(oldTransform:Transform)
{
       yield WaitForSeconds (5);
       var newObject = Instantiate (objectToSpawn , oldTransform.position, oldTransform.rotation);
}

Upvotes: 0

Views: 78

Answers (1)

Joey Quinto
Joey Quinto

Reputation: 367

You are using the old object (destroyed) to choose where to spawn the object. Instead, save the position and rotation into a variable and pass that into the function SpawnAfter5Seconds instead of the null transform.

Upvotes: 1

Related Questions