Hi,
I’ve previously posted a topic without any response but I’ve just decided to use another solution. But as many other developers, I’m stuck once more by a problem I don’t really understand…
I’ve created a function which select all “blocs” suitable from a list and return a random item of the result list :
private function lookForBloc(isSpawn:boolean,faction:String,isBorder:boolean,borders:String){
var resulTab : GameObject[];
var number : int;
var i : int = 0;
for (bloc in blocs)
{
if(bloc.GetComponent(BlocAttributes).isSpawn == isSpawn bloc.GetComponent(BlocAttributes).isBorder == isBorder)
{
if(isBorder bloc.GetComponent(BlocAttributes).borders == borders )
{
if(isSpawn bloc.GetComponent(BlocAttributes).faction == faction )
{
resulTab[i] = bloc;
i++;
}
}
}
}
number = Random.Range(0,resulTab.length);
return resulTab[number];
}
But I get this error : NullReferenceException: Object reference not set to an instance of an object
But if I don’t store the results in an array, it works perfectly.
I don’t understand what goes wrong. I’m storing a GameObject in a GameObject Array …
Thanks.
Error cheking is a great thing… I believe that the selected block does not contain BlocAttributes. Try modifying your script as below:
private function lookForBloc(isSpawn:boolean,faction:String,isBorder:boolean,borders:String){
var resulTab : GameObject[];
var number : int;
var i : int = 0;
for (bloc in blocs)
{
var BA = bloc.GetComponent("BlocAttributes");
if(BA){
if(BA.isSpawn == isSpawn bloc.GetComponent(BlocAttributes).isBorder == isBorder)
{
if(isBorder BA.borders == borders )
{
if(isSpawn BA.faction == faction )
{
resulTab[i] = bloc;
i++;
}
}
}
}
}
number = Random.Range(0,resulTab.length);
return resulTab[number];
}
Thanks for the quick response.
I currently have only 2 blocks and I checked manually that they do have a BlocAttributes component on them …
I tried your code but it still doesn’t work …
The only thing that works is:
private function lookForBloc(isSpawn:boolean,faction:String,isBorder:boolean,borders:String){
var resulTab : GameObject[];
var number : int;
var i : int = 0;
for (bloc in blocs)
{
var BA = bloc.GetComponent("BlocAttributes");
if(BA){
if(BA.isSpawn == isSpawn bloc.GetComponent(BlocAttributes).isBorder == isBorder)
{
if(isBorder BA.borders == borders )
{
if(isSpawn BA.faction == faction )
{
//~ resulTab[i] = bloc;
//~ i++;
return bloc;
}
}
}
}
}
//~ number = Random.Range(0,resulTab.length);
//~ return resulTab[number];
}