- Home /
Help With AI Error
The Error:
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/812c4f5049264fad/Runtime/ExportGenerated/Editor/UnityEngineTransform.cs:19) enemyai.Update () (at Assets/OG_Scripts/Health/enemyai.cs:30),
I set a deadreplacement ragdoll to instansiate after death, but the ai of the enemies would error x20000 and lag till the game crashed,help please.
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxDistance;
private Transform myTransform;
void Awake() {
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 2;
}
// Update is called once per frame
void Update () {
// Debug.DrawLine(target.position, myTransform.position, Color.yellow);
//Look at target
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
Answer by Landern · Mar 15, 2013 at 08:14 PM
If you destroyed on your Player GameObject, then yeah, the reference is hosed and needs to be re-referenced. I assume this is what is happening. You could wrap the Update instructions with.
void Update () {
// Check target is not null.
if(target)
{
// Debug.DrawLine(target.position, myTransform.position, Color.yellow);
//Look at target
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613094503im_/https://answers.unity.com/themes/thub/images/avi.jpg)