- Home /
Problem with destroying a gameObject when used with targeting
I'm using a targeting script on a tutorial (Hack & Slash) and it works fine, but when I made the enemy's health go to 0 and he dies (I used a 'Destroy(gameObject);'). when I destroy the gameObejct the targeting no longer works because it cannot access the destroyed gameObejct. Is there a way of deleting him so I can't target him and he is destroyed, but doesn't affect the other targets? If anyone can make sense of that please help.
Could you post your targetting script? If you're storing an array of targets, you just need to add code where you call Destroy to remove the target from the array. There's possibly something that can be improved in this script to avoid/correct this problem, but without seeing the script, it's kind of hard to guess at the answer to your question.
Answer by MonkeyAssassin8 · Sep 18, 2010 at 01:19 AM
Here is the Targeting Script:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Targeting : MonoBehaviour { public List<Transform> targets; public Transform selectTarget;
private Transform myTransform;
// Use this for initialization void Start () { targets = new List<Transform>(); selectTarget = null; myTransform = transform; AddAllEnemies(); TargetEnemy(); }
public void AddAllEnemies() { GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in go)
AddTarget(enemy.transform);
}
public void AddTarget(Transform enemy) { targets.Add(enemy); }
private void SortTargetsByDistance() { targets.Sort(delegate(Transform t1, Transform t2) { return(Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position))); }); }
private void TargetEnemy() { if(selectTarget == null) { SortTargetsByDistance(); selectTarget = targets[0]; } else { int index = targets.IndexOf(selectTarget);
if(index < targets.Count - 1)
{
index++;
}
else
{
index = 0;
}
DeselectTarget();
selectTarget = targets[index];
}
SelectTarget();
}
private void SelectTarget() { selectTarget.renderer.material.color = Color.white;
PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");
pa.target = selectTarget.gameObject;
}
private void DeselectTarget() { selectTarget.renderer.material.color = Color.white; selectTarget = null; }
// Update is called once per frame void Update () { //I added these so it would select the closest target SortTargetsByDistance(); selectTarget = targets[0]; SelectTarget(); if(Input.GetKeyDown(KeyCode.Tab)) { TargetEnemy(); } }
}
Your answer
Follow this Question
Related Questions
Problem with collisions and Destroy(gameObject). 2 Answers
Clones of object wont disapear.. 1 Answer
Can't destroy a script. 1 Answer