Object reference not set to an instance of an object

Hi everybody

I made a script, which works fine, but it receives a static variable from another script. And because I want to use this script on multiple objects, I wanted to replace those static variables. And I tried it this way:

var enemyProximity : EnemyProximity = enemy.GetComponent(EnemyProximity);
var enemy : GameObject = GameObject.FindWithTag("Enemy");
var destroy : boolean = enemyProximity.destroy;


function Update () {
 if(destroy == true){
 Destroy(gameObject);
 }
}

But Unity displays an error, Object reference not set to an instance of an object, when I use it. How can I fix this problem. There is another script called EnemyProximity, assigned to a different object, which has a boolean variable called destroy, which is set to false when the game starts.

Please help me solve this problem

I’m not a Javascript guy, but I’d say you need to declare “enemy” before you try to do “enemy.GetComponent”.

When you get a script error, it also should tell you what line the error occurred on.

You are attempting to use the enemy variable before it’s initialized. The key difference is enemy is assigned before calling enemy.GetComponent().

var enemy : GameObject = GameObject.FindWithTag("Enemy");
var enemyProximity : EnemyProximity = enemy.GetComponent(EnemyProximity);
var destroy : boolean = enemyProximity.destroy;

function Update () {
  if(destroy) {
    Destroy(gameObject);
  }
}

Note: You should consider using Awake or Start to initialize your variables. This is especially important when referencing other objects which may be initializing themselves.

Do you have a GameObject with the tag enemy? And if you do your going to need an array to keep track of the multiple ones since you seem to want this to be dynamic. Also instead of setting the enemy var in creation. I would recommend making it an array and filling the array with all the enemies in the start function. so something like this

var Enemy : GameObject;

function Start() {
//fill list with a loop of your desire.
}