Destroying gameobject causes console error

So basically I have an enemy that patrols. When my player comes in contact, he dies. After he dies I receive a console error.

Console error: “The object transform has been destroyed but you are still trying to access it”. How do I fix this?

Here is my destroy script:

onCollision

using UnityEngine;
using System.Collections;
using System;

public class onCollision : MonoBehaviour

{
    public void OnTriggerEnter(Collider node)
    {
        if (node.gameObject.tag == "Player")
        {
            Destroy(node.gameObject);
        }
    }
}

The console error sends me to line 15 below:

SmoothFollow

using UnityEngine;
using System.Collections;

public class SmoothFollow : MonoBehaviour
{
    public Transform target;
    public float distance = 3.0f;
    public float height = 3.0f;
    public float damping = 5.0f;
    public bool smoothRotation = true;
    public float rotationDamping = 10.0f;

    void Update()
    {
        Vector3 wantedPosition = target.TransformPoint(0, height, -distance);
        transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping);

        if (smoothRotation)
        {
            Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
            transform.rotation = Quaternion.Slerp(transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
        }

        else transform.LookAt(target, target.up);
    }
}

What behavior do you want your SmoothFollow to do when its target disappears? If you want it to just stop, then you can wrap up everything in your Update function with a null check.

void Update() {
if (target != null) {
//your Update stuff
}
}
1 Like

That’s exactly what I needed, just wasn’t sure how to write it! Thank you!