0

I am trying to set a GameObject active using a script which is not attached to the Object itself.

GameObject SpecificGame = GameObject.Find("GameT" + gameItemSlot);
SpecificGame.SetActive(true);
SpecificGame.GetComponent<gamesTabItem>().gameID = gameID;

Yes, the variables gameItemSlot and gameID are working fine. The script is supposed to set the inactive GameObject "GameT1" active. I get the following error when I try it:

NullReferenceException: Object reference not set to an instance of an object
gamesTab.GenerateTabItem (Int32 gameID) (at Assets/Scripts/gamesTab.cs:104)
System.Collections.Generic.List`1[System.Int32].ForEach (System.Action`1 action) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:361)
gamesTab.UpdateLibrary () (at Assets/Scripts/gamesTab.cs:46)
moneyTime.UpdateDisplay () (at Assets/Scripts/moneyTime.cs:42)
moneyTime.Start () (at Assets/Scripts/moneyTime.cs:31)

As far as I understood the other questions and the documentation, the error says that SpecificGame is not set correctly. I am a Unity and C# noob, sorry for that :p

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • What is the line of code in gamesTab.cs at line 104? – Bijington Mar 08 '19 at 19:30
  • Yes, you understood correctly - if you can't find item it is null. There is nothing more can be said about it based on information you've provided. I used standard debugging guidance as duplicate ("what is NRE"), there are also plenty of questions on searching items in Unity3d that you should look through... If you still can't find solution - make sure to [edit] post with [MCVE] so it can be re-opened (there is no way to know if you even created/registered objects with "GameT*" as name or what is the value of `gameItemSlot` variable) – Alexei Levenkov Mar 08 '19 at 19:33
  • Have you tried debugging to see if the `Find` method return something other than `null`? You should check for null before accessing `SpecificGame`. – fhcimolin Mar 08 '19 at 19:33
  • @Bijington It is the second line. `SpecificGame.SetActive(true);` – Luna Niermann Mar 08 '19 at 19:34
  • Side note: don't add tags to title – Alexei Levenkov Mar 08 '19 at 19:35

1 Answers1

0

Your Find method is most likely returning null. Check for null before using it....

if(SpecificGame != null)
{
SpecificGame.SetActive(true);
//Etc
}

Or you can use safe navigation:

SpecificGame?.SetActive(true);

fhcimolin
  • 616
  • 1
  • 8
  • 27