My GUI for the game shows a thumbnail for the objects that the Player is carrying with him.
Whenever a player is carrying an object they become his ‘children’.
For this I have a script on each object that loads a specific Texture2D.
My goal is that, when the player is not carrying anything it shows the default texture, otherwise it will read the script inside each of the children and show their respective thumbnail.
This is what I have so far:
function OnGUI () {
// GUI for Player Items //
playerObjects = GameObject.Find("PLAYER").GetComponentsInChildren(Obj_Properties);
var imageWidth : int = 96;
var frameDistance : int = 0;
GUI.BeginGroup (Rect ((Screen.width * 0.5) - (totalFrameDistance * 0.5), 0, totalFrameDistance, 64 ), "");
GUI.Box (Rect (frameDistance,0,imageWidth,64), GUIContent("", PlayerObjSlot_00));
frameDistance += imageWidth +10;
GUI.Box (Rect (frameDistance,0,imageWidth,64), GUIContent("", PlayerObjSlot_01));
frameDistance += imageWidth +10;
GUI.Box (Rect (frameDistance,0,imageWidth,64), GUIContent("", PlayerObjSlot_02));
frameDistance += imageWidth +10;;
GUI.Box (Rect (frameDistance,0,imageWidth,64), GUIContent("", PlayerObjSlot_03));
frameDistance += imageWidth +10;
GUI.Box (Rect (frameDistance,0,imageWidth,64), GUIContent("", PlayerObjSlot_04));
frameDistance += imageWidth;
totalFrameDistance = frameDistance;
GUI.EndGroup ();
PlayerObjSlot_00 = playerObjects[0].GetComponent(Obj_Properties).objThumbnail;
PlayerObjSlot_01 = playerObjects[1].GetComponent(Obj_Properties).objThumbnail;
PlayerObjSlot_02 = nullTexture;
PlayerObjSlot_03 = playerObjects[3].GetComponent(Obj_Properties).objThumbnail;
PlayerObjSlot_04 = playerObjects[4].GetComponent(Obj_Properties).objThumbnail;
My current character has 2 objects and those show correctly but all the other 3 slots, since the children don’t actually exist I get a ‘Array index is out of range.’.
I tried to prevent that by writing these lines but they dont seem to work. How do I write something that understand when the array children dont exist?
if (playerObjects[3] != null){
PlayerObjSlot_03 = playerObjects[3].GetComponent(Obj_Properties).objThumbnail;
}
else {
PlayerObjSlot_03 = nullTexture;
}
if (playerObjects[4] != null){
PlayerObjSlot_04 = playerObjects[4].GetComponent(Obj_Properties).objThumbnail;
}
else {
PlayerObjSlot_04 = nullTexture;
}
Hope the question is clear! Help is very welcome!