Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to Check and update array if a Transform in it has been destroyed

Discussion in 'Scripting' started by cryptoshaman, Feb 27, 2013.

  1. cryptoshaman

    cryptoshaman

    Joined:
    Oct 10, 2012
    Posts:
    15
    I am checking for trigger enter and assigning objects to an array. I then check for distance and shoot at the nearest by. The problem is that when I shoot and destroy and object in the array I can not shoot the next one closer to me because I need to update the array. I get this error when I destroy the object in the array.

    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.

    and here is the script

    Code (csharp):
    1. #pragma strict
    2.  
    3. import System.Linq;
    4.  
    5. var AllEnemies = new List.<Transform>(10);
    6. var enemyTransforms = new List.<Transform>();
    7. var targetTransform : Transform;
    8. var targetVolume: GameObject;
    9.  
    10. function OnTriggerEnter (other : Collider) {
    11.   if (other.CompareTag ("enemy")) {
    12.     for (var n=0; n < 10; ++n) {
    13.  
    14. enemyTransforms[n] = GameObject.Find("boonCreature"+(n+1)).transform;}
    15. }
    16. }
    17.  
    18. function OnTriggerExit (other : Collider) {
    19.  if (other.CompareTag ("enemy")) {
    20.     for (var n=0; n < 10; ++n) {
    21.  
    22. enemyTransforms[n] = GameObject.Find("boonCreature"+(n+1)).transform;}
    23. }
    24. }
    25.  
    26. function  LateUpdate() {
    27.  
    28.     var position = targetTransform.position;
    29.     var nearest = enemyTransforms.OrderBy(function(t){ return (position - t.position).sqrMagnitude; }).First();
    30.     var latestNearest= nearest;
    31.         Debug.Log("this is nearest"+nearest);
    32.  
    33. transform.LookAt(nearest,targetVolume.transform.up);
    34.  
    35.  
    36.  if(enemyTransforms[0] != null){
    37.     for (var n=0; n < 10; ++n) {
    38. enemyTransforms[n] = GameObject.Find("boonCreature"+(n+1)).transform;}
    39. }
    40. }
     
    Last edited: Feb 27, 2013