NullReferenceException... but it was just set...?
I have a Main scene. In this scene, I have an object called "GameController" which is where I'm keeping things like the overall score and other objects that the game needs. One is a list:
public List<myClass> myclassList = new List<myClass>();
In a second scene, I add items to the list. When I get back to the Main scene, it does give me the correct/expected Count of items in the list. But something is screwy when I'm trying to access the members of the list.
To troubleshoot, in the GameController Update method, I added the following:
if (myclassList.Count > 0) {
Debug.Log (myclassList [0].astringfrommyclass);
}
And here's the weirdness... in my console, on the first Update, I get one correct output message with the expected string that's in astringfrommyclass. But that's it. then I keep getting the NullReferenceException on that line of code.
Help??
This is in Unity 2017.3.0f3 and while I'm a relatively experienced programmer, I'm new to Unity.
Even though your list is not empty, it may contains null elements, explaining your error. How and where do you populate your list?
If that's the case, that would make sense. In my Scene2, I have a button called "Save". When "Save" is clicked, this function is called and this is how my list gets populated:
public void Save$$anonymous$$yClassInstance() {
// Get myClass name... from a UI edit text element
string myClassName = myClassNAmeInput.text;
// Create a new myClass object
$$anonymous$$yClass new$$anonymous$$yClass = new $$anonymous$$yClass (myClassName );
// Save the myClass object to the List from the GameController
GameController.Instance.myclassList.Add(new$$anonymous$$yClass );
// Return to main scene
Scene$$anonymous$$anager.LoadScene("$$anonymous$$ain");
}
@hellium I think you gave me some ideas of things to look at.... I guess what I should be doing is to create a new GameObject and somehow that object is tied to the new instance of myClass...? I'm still learning Unity and it's a little different from what I'm used to with object scope because of these "GameObject" things. I just found this post: https://answers.unity.com/questions/1178271/passing-an-instance-of-a-class-to-different-game-o.html
and that might help lead me to my answer....???
Answer by OneCept-Games · Jan 07, 2018 at 12:03 PM
Scenes are not persistent to each other. If you want to save your values from one scene to the other, you will have to either store your data using PlayerPrefs or UnityEngine.IO, or use Singleton approach on your script and then DontDestroyOnLoad();
I do have a DontDestroyOnLoad in my GameController. In my GameController I have this function:
void Awake ()
{
if (Instance == null) {
DontDestroyOnLoad (gameObject);
Instance = this;
} else if (Instance != this) {
Destroy (gameObject);
}
}