- Home /
What's the better practice to use common variable?
I am new to coding so please bear with me. I am trying to optimizing my code. As far as I read, there are few ways to access common variables.
Most obvious: using static variable
public class Scoring : MonoBehaviour { public static int TotalCatCollected; private bool touchCat; void Update() { if (touchCat) //touch cat TotalCatCollected++; } } public class Acheivement : MonoBehaviour { private int Acheivement; void UnlockAcheivement() { if (Scoring.TotalCatCollected>10) Acheivement =1; } }
Use Accessor (forgive me if the word usage is wrong)
public class Scoring : MonoBehaviour { public int TotalCatCollected; private bool touchCat; void Update() { if (touchCat) //touch a cat TotalCatCollected++; } } public class Achievement : MonoBehaviour { private int Achievement; private SomeScript someScript; void UnlockAcheivement() { someScript = GameObject.Find("Player").GetComponent<Scoring>(); if (someScript.TotalCatCollected > 10) Achievement=1; } }
Use PlayerPref
public class Scoring : MonoBehaviour { private int TotalCatCollected; private bool touchCat; void Update() { if (touchCat) //touch a cat { TotalCatCollected++; PlayerPrefs.SetInt("TotalCatEver",TotalCatCollected); } } } public class Achievement : MonoBehaviour { private int Achievement; void UnlockAcheivement() { if (PlayerPrefs.GetInt("TotalCatEver") > 10) Achievement=1; } }
So the question is what is the better practice (in term of processor,memory usage, code maintenance)? From my (very limited) understanding:
Usage of global variable should be very restricted. But I feel (maybe incorrectly) it's faster.
PlayerPrefs read and write system files for different OS so it's slower and (somewhat) unstable
Usage of Accessor seems heavy because finding gameObject is costly.
None of these are necessarily appropriate in the situation your examples are attempting to illustrate. I'm not sure these scripts will compile or run just by looking, but your question is clear enough.
Generally speaking, you should form explicit relationships between objects wherever possible. Nine times out of ten, you can avoid using the GameObject.Find family of methods altogether. (I have exactly zero of them in my year-long project.) In Unity, avoiding "finds" often involves exposing a public variable of the type you need, and assigning the desired instance to that exposed variable in the inspector. That's all it takes to get two script instance talking to each other.
When you're creating objects dynamically, often the code which creates them can be followed by lines of code to GetComponents or assign necessary references. $$anonymous$$eeping a collection of such objects makes it easy to make changes to them after the fact.
When this is not possible, convenient, or sensible, the next step out is a managerial class. Things like a GameState$$anonymous$$anager to control the flow of execution, or an AudioEffects script you can call from anywhere to request a foley sample - these things should only exist once in the scene, so it makes sense for them to be Singletons.
Use PlayerPrefs to store things like resolution settings, music volume, and assorted game settings - it's not especially wise to use it for anything else.
The code is for illustration only, the purpose is to show the logic behind each practice (and if I understand them correctly).
What I gather from your comment is something like this:
Avoid .Find AND avoid static variable as well (even though it was not specifically expressed).
In this case: a character collect coins, coins disappear, total amount of coins collected so far is displayed on a UI item. Does this case justify the use of static variable? If it's not the good practice, what should be applied in this case? (Very beginner question, sorry)
Use GetComponents wherever possible
What's the alternative to PlayerPref? For now, I am storing game highscore, total score and achievement (which unlock features in game) and few other in PlayerPref. It's not yet too complex to handle but in the next version, I plan to store arrays of things.
I guess don't worry about using PlayerPrefs for now; just use it as you like. Later, when you want to store more complex objects, you'll learn about serialization and read/write operations. It would be a lot to bite off this early in your career though, so lean on PlayerPrefs as needed till you get that far. Just know that its true purpose is for storing application preferences.
I don't normally approach data management in such a way that I need static variables in the way you describe. In your illustration, I would create a Level class, and let my Singleton GameState$$anonymous$$anager instance keep an instance of a Level object as the activeLevel.
Then, when collecting a coin, I could write....
GS$$anonymous$$.ActiveLevel.Coins.Remove(coin);
GS$$anonymous$$.ActiveLevel.coinsCollected++;
and when displaying the count,
label.text = GS$$anonymous$$.ActiveLevel.coinsCollected.ToString();
I don't need a reference to the GS$$anonymous$$ object, because it's a singleton. And during initialization logic, my Level object gets created by (or at least gets handed to) the GS$$anonymous$$ instance, so I never need to get or keep a reference to said Level object.
This kind of design pattern is great to work with. It encourages clean and structured execution flow, smart instance management, and offers convenient access to any script anywhere in your project. (Obviously it's not appropriate for everything; just things "like this" where you need access to a single object all over the project, like "the current level".)
These are practices you'll pick up as you go. For right now, just do what makes sense to you so you don't get bogged down in these intermediate concepts. It'll come. :)
@AlwaysSunny Thanks so much for your opinion and advices.