- Home /
Problem with targeting system
I have a targeting system and it will target an enemy and than ill fight them and kill them and than once i kill them in the enemy ai script i have this
For my Player script i am using system.collections.generic
if(Health <= maxHealth) {
Destroy(transform.gameObject);
}
Once the object gets destroyed i get 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.
UnityEngine.Transform.get_position () (at C:/BuildAgent/work/842f9557127e852/Runtime/ExportGenerated/Editor/UnityEngineTransform.cs:19)
PlayerController.<SortTargets>m__0 (UnityEngine.Transform t1, UnityEngine.Transform t2) (at Assets/My Assets/Scripts/Player/PlayerController.cs:65)
System.Array.qsort[Transform] (UnityEngine.Transform[] array, Int32 low0, Int32 high0, System.Comparison`1 comparison)
System.Array.Sort[Transform] (UnityEngine.Transform[] array, Int32 length, System.Comparison`1 comparison)
After getting this error i am no longer able to target. I know what the error means but i dont know how to fix.
Heres the code that the errors is in
public void Targeting() {
GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in go){
AddTarget(enemy.transform);
}
}
public void AddTarget(Transform enemy){
targets.Add(enemy);
}
private void SortTargets() {
targets.Sort(delegate(Transform t1, Transform t2) {
return Vector3.Distance(t1.position, transform.position).CompareTo(Vector3.Distance(t2.position, transform.position));
});
}
public void ActualTarget() {
if(Target == null) {
SortTargets();
Target = targets[0];
}
else
{
int index = targets.IndexOf(Target);
if(index < targets.Count - 1) {
index++;
}
else
{
index = 0;
}
DeselectTarget();
Target = targets[index];
}
SelectTarget();
}
private void SelectTarget() {
Target.renderer.material.color = Color.red;
SelectedEnemy = Target.gameObject;
}
private void DeselectTarget() {
Target.renderer.material.color = Color.yellow;
Target = null;
}
void Update() {
if(SelectedEnemy == null) {
ActualTarget();
}
if(Input.GetKeyDown(KeyCode.Tab)){
ActualTarget();
}
}
I obviously have the variables for this or it wouldnt work in the first place.
You need to have some kind of system that automatically removes null references from your array if the transform in question has been destroyed.
hmm, i have an idea on how to do it but i dont know how to remove it from the list
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Targeting multiple tiles in grid, updating with player movement 1 Answer