- Home /
Changing AI target, after destroying gameObject
Hello. I am working on a game where I have minions fighting. My problem is that when I destroy the first target, I cannot reset a new target for the minion. This is what the console says:
Your script should either check if it is null or you should not destroy the object. Please, if someone could tell me what is wrong with my code I will be very grateful, as the last 7 hours I have been trying to find a solution without success. public class aController : MonoBehaviour { public Transform target; public int moveSpeed; public int rotationSpeed; public float atackDistance;MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
private Transform myTransform; private GameObject go;
void Awake(){ myTransform = transform; }
// Use this for initialization void Start () { SetTarget(); }
// Update is called once per frame void Update () { Debug.DrawLine(target.transform.position, myTransform.position, Color.yellow);
//finds target if (target == null) { SetTarget (); }
//Look at target myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed Time.deltaTime);
if ((Vector3.Distance(target.position, transform.position)) > atackDistance)//Move until in range to atack { //Move towards target myTransform.position += myTransform.forward moveSpeed * Time.deltaTime; } else{ atack (); } }
void SetTarget() { go = GameObject.FindGameObjectWithTag("teamB"); target = go.transform; }
void atack() { //ATACK CODE HERE... } }
Perhaps wrap an:
if(target != null)
{
}
Around the whole area starting from //Look at target, and end after else{}. ? Perhaps for a frame, there exists no object with $$anonymous$$mB and it falls over on itself.
Another though would be to change
myTransform = transform;
to
myTransform = this.gameObject.transform;
Answer by robertbu · Jan 19, 2014 at 04:31 PM
Just because you destroy something doesn't mean the reference to that object becomes null. You have a couple of choices here. A bit hackish but easy solution would be to call SetTarget() in Start() and at the top of Update(). That will make sure that 'target' is a valid transform. If you don't go that route, then you are going to have to somehow inform this code that the target has been destroyed and therefore it should acquire a new target. You could do that by the projectile directly referencing the code (GameObject.Find() and GetComponent()) or by SendMessage(). A bit cleaner (IMHO) but a bit more complex solution would be to use C# events and delegates:
http://answers.unity3d.com/questions/600416/how-do-delegates-and-events-work.html