Search code examples
unity-game-engineunityscript

Unity NullReferenceException after accessing a variable of another script


after trying to acces a variable in another Script of another GameObject out of a List, I get every time an Exception. The Main code looks like this:

private var BombList = new List.<GameObject>();
private var BombTemp : GameObject;
private var BombTempScript : Bomb;
function Start () {
    BombTemp = null;
    BombTempScript = null;
    BombList.Clear();
}
function Update () {
if(BombList.Count > 0){
        for(var i : int = 0; i<BombList.Count;i++){
            BombTemp = BombList[i];
            BombTempScript = BombTemp.GetComponent.<Bomb>();
            if(BombTempScript.bombCountdown <= 0){
                BombTempScript.explode();
                BombList.Remove(BombTemp);
                addHealth(-1);
            }
        }
    }
}

function OnTriggerEnter (other : Collider) {
if(other.gameObject.CompareTag("Bomb")){
        BombList.Add(other.gameObject);
        other.gameObject.GetComponent.<Bomb>().notListed = false;
    }
}
function OnTriggerExit(other : Collider){
    if(other.gameObject.CompareTag("Bomb")){
        if(BombList.Contains(other.gameObject)){
            BombList.Remove(other.gameObject);
            other.gameObject.GetComponent.<Bomb>().notListed = true;
        }
    }
}

If there isn't an object in the List the Code in the Update function does not work as intended. But when there is an object inside it produces a NullReferenceException in the if Line:

if(BombTempScript.bombCountdown <= 0)

The variable which is pointed at named bombCountdown, is continuously changing. Here is the intended code:

#pragma strict
public var bombCountdown : float;
public var notListed : System.Boolean;

function Start () {
    bombCountdown = 10.0;
    notListed = true;
}

function Update () {
    bombCountdown -= Time.deltaTime;
    if(bombCountdown <= 0 && notListed)
        explode();
}
function explode(){
    Destroy(myText);
    Destroy(this.gameObject);
}

I hope you could help us.

Thanks in advance, the Silly Scientists


Solution

  • I think there's a small bug in the code, which is making it happen.
    In the Bomb script, in the following portion, you are destroying the bomb object, without removing it from the BombList of the first script.
    enter image description here

    As a result, BombList[i] may become null, as it may already have been destroyed.
    enter image description here

    If you make sure that you update the BombList when the Bomb is destroyed, I guess the code will work.