Question by
codycolombrito · Jun 20, 2016 at 12:45 AM ·
c#nulldestroy object
How to fix MissingReferenceException?
I have ran into an issue with a 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.
The compiler issue is located at the DistanceToTarget function.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class HomingMissle : MonoBehaviour {
public List<Transform> enemies;
public Transform selectedTarget;
private ShipPlayerController parentShip;
// Use this for initialization
void Start () {
selectedTarget = null;
enemies = new List<Transform>();
AddEnemiesToList();
GameObject playerShip = GameObject.Find("PlayerShip");
parentShip = playerShip.GetComponent<ShipPlayerController>();
//Destroy(gameObject);
}
// Update is called once per frame
void Update () {
TargetedEnemy();
float dist = Vector3.Distance(selectedTarget.transform.position, transform.position);
if(dist < 150)
{
transform.position = Vector3.MoveTowards(transform.position, selectedTarget.position, 5 * Time.deltaTime);
}
}
public void AddEnemiesToList()
{
GameObject[] ItemsInList = GameObject.FindGameObjectsWithTag("EnemyShip");
foreach(GameObject _Enemy in ItemsInList)
{
AddTarget(_Enemy.transform);
}
}
public void AddTarget(Transform enemy)
{
enemies.Add(enemy);
}
public void DistanceToTarget()
{
enemies.Sort(delegate(Transform t1, Transform t2){
return Vector3.Distance(t1.transform.position, transform.position).CompareTo(Vector3.Distance(t2.transform.position, transform.position));
});
}
public void TargetedEnemy()
{
if(selectedTarget == null)
{
DistanceToTarget();
selectedTarget = enemies[0];
}
}
void OnTriggerEnter (Collider other)
{
if(other.tag == "EnemyShip")
{
Destroy(gameObject);
parentShip.ModScore(1);
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612083255im_/https://answers.unity.com/themes/thub/images/avi.jpg)