How to fix this script

Hello,

I have this script called AIDestroy, needed to eliminate the game object from the game itself (in order to reduce graphic lag) but the problem is that sometimes is not working.

The script :

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AIDestroy : MonoBehaviour {
	public bool destroyai;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		
	if(destroyai){
		AI ai=(AI)GetComponent("AI");
			if(ai){
			int flist=ai.friendly.Count;
				if(ai.friendly.Count>0){
		for (int f = 0; f < flist; f++){
					AI aif=(AI)ai.friendly[f].GetComponent("AI");
						if(aif){
					if(aif.companionleader=null){
						aif.companionleader=null;
						aif.companion=false;
						aif.targetlocateto=null;
						aif.gototarget=false;
						aif.gototargetnostop=false;
						aif.idle=true;
					}
					}
					}
				}
				
				if(ai.enemys.Count>0){
				int elist=ai.enemys.Count;
		for (int i = 0; i < elist; i++){
					AI aie=(AI)ai.enemys*.GetComponent("AI");*
  •  				if(aie){*
    
  •  		if(aie.enemy==transform){*
    
  •  				aie.enemy=null;*
    
  •  				if(aie.attack){*
    
  •  					aie.attack=false;*
    
  •  					if(aie.targetlocateto)aie.gototarget=true;*
    
  •  					else aie.idle=true;*
    
  •  				}*
    
  •  			}*
    
  •  		aie.enemys.Remove(transform);*
    
  •  			}*
    
  •  			}*
    
  •  	}*
    
  •  		Destroy(gameObject);*
    
  •  }*
    
  •  	}*
    
  • }*
    }
    The 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.
    Pointing to the line with: AI aif=(AI)ai.friendly[f].GetComponent(“AI”);
    Usually the script goes on error spree after the second unit of the same type dies.
    Please help :smiley:

Try this: put an extra line in your code like this

 if(destroyai){
 destroyai = false;// this is an extra line
AI ai=(AI)GetComponent("AI");
if(ai){
...
...

Check to make sure it’s not null before you use it.

Transform t = < the transform>;
if (t == null) continue;
// t.GetComponent...