Variables not updating c# [SOLVED]

So I have a GameMaster class and PlayerMovement class. In PM, I have a public bool “win” which is set to False in Start(). It changes to True once the player collides with the objective. In GM, a function is called from PM that returns the status of “win”.

So here’s the problem; “win” always returns false in GM, even if “win” is true in PM. I need to figure out how to have “win” correctly update across my entire program.

After hours of testing, I have figured out these things:

  1. It is set to a null value when called in GM. I confirmed this by changing the bool to an int. No matter what number I set the initial value to, it always returned 0 in GM.
  2. This only happens to public functions in PM. Any non public function receives the correct status of the variable.
  3. If the check method is called in PM, it returns the correct status. If called in GM, it always returns false.

This question has been asked before here, but it was never answered. If you need me to provide my code, just ask. Thank you.

[SOLVED] If you are using a struct, you need to make the variable you need static. OR, use a class instead. A C# struct is read only when called from a function, but a class doesn’t have this problem. See here for more detail: Can't modify Struct variables C# - Questions & Answers - Unity Discussions

1 Answer

1

I’ve found recently that objects that are “off” cause their scripts’ Start()s to never be called. I would suggest printing there to be sure that Start() is even being called.

Also, are you sure that GM has the right pointers? It’s possible that GM is creating PMs to point to that are never instantiated, while other PMs are being run and not interacting with the GM. To avoid this, I’ve been making such pointers public in my games, so I can set them directly in the inspector.

So I checked and yes, Start() is being called, and Gm does have the right pointers. Luckily, after messing around with it a bit more, I discovered a workaround. Instead of using a variable between two classes, I just had PM call a function from GM, complete negating the need for the variable. But thank you for helping. To anyone who has this problem down the road, I don't know if it can be solved, but try to see if you can work around it by calling a function instead of a variable. Good luck!

Instantiate places an object in your scene hierarchy (i.e. it creates an instance of a prefab). The reason for assigning the result of instantiate to a variable is if you then want to do something with that gameobject after creating it.