- Home /
(Targetting) error object is destroyed
Hi all, little bit of a n00bish question, i know what* the problem is and i know what* i need to do i just dont know how** to do it :), ive been slowly learning unity and c# mainly thru a rpg tutorial, altering bits from the tutorial as i go now ive come to a little issue ive got a targetting script which adds all items with the tag "mob" and i can cycle thru the mobs no problem, but as ive added other scripts of my own ive ran into an error mainly when i "Kill" the mob and destroy the game object the targetting script pops up an error, (The object of type 'Transform' has been destroyed but you are still trying to access it.) im assuming this means it is not repopulating the list properly, can someone explain where and how i would implement refreshing the list, again sorry for such a simple question im just not sure on the syntax and placement
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class targetting : MonoBehaviour {
public List<Transform> targets;
public Transform selectedTarget;
private Transform myTransform;
// Use this for initialization
void Start () {
targets = new List<Transform>();
selectedTarget = null;
myTransform = transform;
AddAllEnemies();
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Tab)) {
TargetEnemy();
}
}
public void AddAllEnemies() {
GameObject[] go = GameObject.FindGameObjectsWithTag("mob");
foreach(GameObject enemy in go) {
targets.Add(enemy.transform);
}
}
private void TargetEnemy() {
if(selectedTarget == null) {
SortTargetsByDistance();
selectedTarget = targets[1];
} else {
int index = targets.IndexOf(selectedTarget);
if(index < targets.Count - 1) {
index++;
} else {
index = 0;
}
DeselectTarget();
selectedTarget = targets[index];
}
SelectTarget();
}
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 SelectTarget() {
selectedTarget.renderer.material.color = Color.red;
playeratt pa = (playeratt)GetComponent("playeratt");
pa.target = selectedTarget.gameObject;
}
private void DeselectTarget() {
selectedTarget.renderer.material.color = Color.gray;
selectedTarget = null;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
i need help removing an error in my targetting/attack script 1 Answer
c# help fix argument is out of range error 1 Answer
Ignoring Vector3.MoveTowards() 0 Answers