Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by youngexplorer · Mar 17, 2015 at 03:41 PM · variableplayerprefsstaticaccessor

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.

  1. 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;
             }
         }
     
    
    
     
    
    
  2. 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;
             }
         }
    
    
    
     
    
    
    
  3. 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.

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image AlwaysSunny · Mar 17, 2015 at 03:25 PM 0
Share

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.

avatar image youngexplorer · Mar 17, 2015 at 05:58 PM 0
Share

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.

avatar image AlwaysSunny · Mar 17, 2015 at 06:19 PM 1
Share

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. :)

avatar image youngexplorer · Mar 20, 2015 at 10:11 AM 0
Share

@AlwaysSunny Thanks so much for your opinion and advices.

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Trivial question for Javascript/Unityscript experts: static variables? 4 Answers

How to make a var "global" 0 Answers

How can i save a int for multiple texture. Please Read. 0 Answers

Prefab's Script affecting all the Prefab 1 Answer

Static, yet Private, Variables? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges