[Solved] Null Reference Exception on a text variable
Hi guys
I'm working on a script for a wave spawner when i lauch the game the script start i get this error :
NullReferenceException: Object reference not set to an instance of an object ZombieGameMode.Update () (at Assets/Mes Asset/Script/JeuInfo/ZombieGameMode.js:50)
I've checked in the Inspector and both of the variable are set i've try a lot of thing and it doesn't fix it (Sorry for my english i'm frebch btw)
Here is my script :
#pragma strict
import UnityEngine.UI;
var Second : int = 00;
var Minute : int = 00;
var Wave : int = 00;
var WaveTimer : int = 00 ;
var boucle : boolean = false;
var TimerUI : Text ;
var WaveUI : Text ;
var ennemy1 : GameObject;
private var spawnSpawner : int ;
private var SpawnNumber : int ;
var Spawn : int ;
var SpawnCount : int = 10 ;
public var AllSpawner : GameObject[];
function Start () {
AllSpawner = GameObject.FindGameObjectsWithTag("Spawner"); ;
SpawnNumber = AllSpawner.length ;
}
function Update () {
//Veriffier toute les frame les seconde
if (boucle == false){
Secondcount();
boucle= true ;
}
if(Second == 60){
Minute = Minute + 1;
Second = 0 ;
}
if(Minute == WaveTimer ){
WaveTimer = WaveTimer +1;
Wave = Wave + 1 ;
SpawnCount = SpawnCount*1.5 ;
Spawns();
}
//Ubdate le time
TimerUI.text= Minute+" : "+Second;
//Ubdate les wave
WaveUI.text = "Wave : "+ Wave ;
}
function Spawns(){
spawnSpawner = SpawnCount/SpawnNumber ;
for(var i=0; i < spawnSpawner;i++){
for(var Place : GameObject in AllSpawner){
yield WaitForSeconds(1);
var position = Place.transform.position ;
Instantiate (ennemy1,position,transform.rotation) ;
}
}
}
//Ajouter une seconde toute les seconde
function Secondcount(){
Second = Second + 1 ;
yield WaitForSeconds(2);
boucle = false ;
}
And i've forgot to says that the game start and the scripts seems to work but i still get this error in the console .
Answer by RecyclingBen · Mar 22, 2017 at 11:31 AM
Looks like something in your script is trying to reference something that does not exist (YET!!)
It's completely possible that what it is trying to reference has not been created in the first couple frames of the game, so you get the error at the start of it.
It's good practice to check if a referenced object != null before using it (I'm a complete hypocrite on that)
So if your game is working 100% fine just use an if statement like
if (objectImReferencing != null) { use objectImReferencing normally in here}
that way even if the object isn't created yet you don't get a NullReferenceException
Thanks you that worked for me for people how want an exemple i've changed
//Ubdate le time
TimerUI.text= $$anonymous$$inute+" : "+Second;
//Ubdate les wave
WaveUI.text = "Wave : "+ Wave ;
To :
if (TimerUI == !null && WaveUI == !null ){
//Ubdate le time
TimerUI.text= $$anonymous$$inute+" : "+Second;
//Ubdate les wave
WaveUI.text = "Wave : "+ Wave ;
}