- Home /
MissingReferenceException Help
I want the enemy objects that I created to be destroyed when they hit my player, but instead I keep receiving the Missing Reference Exception Error. Here are the two scripts involved with the enemy object. Any help is appreciated.
ColliderScript, which is attached to the enemy prefab
var enemy: Object;
function Start(){
}
function OnTriggerEnter (enemy: Collider)
{
if(enemy != null)
{
Destroy(enemy.gameObject,2);
enemy = null;
}
}
This is the enemy script which is attached to the enemy prefab
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
I keep receiving this 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.
What should I do?
Answer by Kryptos · Sep 11, 2012 at 09:30 AM
You destroyed the player instead of the enemy in the first script. Therefore the target variable in the second script is a reference to a destroyed object.
So either put the first script on the player, or change it so that it destroys itself instead of destroying the player:
function OnTriggerEnter (collider: Collider)
{
// you should better check that the collided object is in fact the player
// try something like
// if (collider != null && collider.gameObject.tag == "Player")
if(collider != null)
{
Destroy(this.gameObject, 2);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Acces to other object trigger thru other object script 0 Answers
Destroyed Object Error 2 Answers
how can I check if an object is null? 4 Answers