- Home /
Change target after destroying it.
Hello guys. I was hoping you guys can help me! I am making a game where minions fight, and I want that after a minion kills another, he changes his target to other minion. However I get this error after destroying the gameObject.
Your script should either check if it is null or you should not destroy the object. I leave you my code so if you guys can please point me in the right direction or tell me what I am doing wrong, I would be very grateful!!! 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... } } Thank you!
Answer by nesis · Jan 19, 2014 at 02:47 PM
Your Debug.DrawLine() method is referencing the target variable, which might be null at that point. Your target==null if statement should be right at the start of your Update() method :)
An aside: since you're destroying things you're targeting, I'm presu$$anonymous$$g there'll be a case when there's nothing left to target... so you should check that inside your target==null if statement, and return / disable the script to avoid errors. Your go = GameObject.FindGameObjectWithTag("$$anonymous$$mB")
will set go
to null if no GameObject with that tag could be found.
Answer by UnPluks · Jan 19, 2014 at 03:48 PM
Oh my god, that solved everything. I feel so dumb now! Thank you, I really appreciate your help. Happy Coding! :D (I will share my code once I finish the game :))