- Home /
Array assignments not behaving as expected.
I am getting the warning "savedMat is never assigned to and will always have its default value null" when building this script. I am definitely assigning to it in the Start function, however the warning appears to actually be correct because later in the script I get null reference exceptions. What am I doing wrong?
private GameObject[] findRobots;
private Material[] savedMat;
public Material eyeMaterial;
// Use this for initialization
void Start () {
findRobots = GameObject.FindGameObjectsWithTag("GuardBot");
if(findRobots.Length==0 || findRobots == null){
Debug.Log ("No objects tagged as \"GuardBot\", RobotEyes will not work.");
return;
}
for(int n=findRobots.Length; n<findRobots.Length; n++){
savedMat[n] = findRobots[n].renderer.material;
}
}
Answer by Kiloblargh · Feb 24, 2014 at 03:41 AM
Before assigning anything to a slot in an array, you have to initialize the array with new
and the size:
savedMat = new Material [findRobot.Length];
Answer by rutter · Feb 24, 2014 at 03:41 AM
Seems like you need something closer to this:
savedMat = new Material[findRobots.Length];
for(int n=0; n<findRobots.Length; n++){
savedMat[n] = findRobots[n].renderer.material;
}
You need to create the array before you can populate it.
EDIT: Never$$anonymous$$d, figured it out! Simple mistake on my part, the for loop declaration only filled the last object.
Thanks! That fixed them being empty, but now the actual populate script isn't running. It no longer throws an error, but the material that is being saved in saved$$anonymous$$at[n] is empty. (Shows up as pink in game) The materials of the gameObjects in findRobots are definitely not empty. Any idea what's wrong with the for loop?
I ran it with a Debug.Log in the loop and it never gets called.
Because you are starting it at the end. If n starts out as findRobots.Length
and increments, it will never be less than`findRobots.Length.` The for loop should start with 0.