Getting 'object reference not set' after deactivating objects & activating them
I'm building a character selection screen for 2 players to select from a choice of 3 characters. I present the GameObjects in the interface (named Player1A, Player1B, Player2A etc) and want to disable/enable them when selected. I haven't got very far, I'm stuck on hiding them all initially, where I loop through them all and unhide the ones I want initially selected.
But I get the error "Object reference not set to an instance of an object" when finding the object a 2nd time. What should I be doing in this case, using a multidimensional array to store references to the gameObjects? That seems complex to me (I'm not such a strong programmer!). Is there an easier way to do what I'm doing? Any tips would be useful. Thanks! Here's my code:
//--create array of the possible different player characters
public var playerCharacters = new Array ("A", "B");
private var numPlayers : int = 2;
function Start () {
//--hide all the characters, then show the 1st ones
for(var i : int = 1; i <= numPlayers; i++){
for(var j : int = 0; j < playerCharacters.length; j++){
Debug.Log("hide Player"+i+playerCharacters[j]);
GameObject.Find("Player"+i+playerCharacters[j]).SetActive(false);
}
}
GameObject.Find("Player1A").SetActive(true);
GameObject.Find("Player2A").SetActive(true);
}
Answer by Firedan1176 · Dec 31, 2015 at 03:38 AM
GameObject.Find only returns active GameObjects, so you can't them when they're disabled! What I would suggest is first, create an empty GameObject to store all your Players (called "Players"). Then, create a List of all of your GameObjects in your script (instead of an array), then simply grab the one you need with an index. I'm not familiar with JavaScript in Unity since I use C#, but I will give you a C# example, which you can then decipher.
public List<GameObject> players = new List<GameObject>();
int currentlyEnabled = 0;
void Start() {
GameObject[] foundPlayers = GameObject.Find("Players").GetComponent<GameObject>();
foreach(GameObject g in foundPlayers) players.add(g);
}
void PerformAction() {
//This is where you'd change players.
players[currentlyEnabled].SetActive(false);
currentlyEnabled++;
players[currentlyEnabled].SetActive(true);
}
And your hierarchy:
Players
-->A
-->B
Now remember, this is C#, so you'll need to do some changes.
Your answer
Follow this Question
Related Questions
UI problems 0 Answers
Navigating multiple menus & scenes 0 Answers
Options menu won't work 0 Answers
How to create scene with multiple panels? 0 Answers
WEIRD EVENT SYSTEM BUTTON SELECTION 0 Answers