The question is answered, right answer was accepted
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:
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.
This only happens to public functions in PM. Any non public function receives the correct status of the variable.
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: https://answers.unity.com/questions/425510/cant-modify-struct-variables-c.html
Answer by Thajocoth · Jun 19, 2016 at 04:43 AM
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. Ins$$anonymous$$d of using a variable between two classes, I just had P$$anonymous$$ call a function from G$$anonymous$$, 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 ins$$anonymous$$d of a variable. Good luck!
Well, I'm glad you figured out a workaround at least. Good luck with the rest of your project!
Follow this Question
Related Questions
When my "Player" teleport it goes back to his last position 2 Answers
How to update variable based on scene 0 Answers
double output even though it should be possible C# 1 Answer
Variable containing a transform is modifying the object's transform it is referenced to. 1 Answer
How do I compare if a variable of integer type is between two values 1 Answer