Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 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 TheLagbringer · Jul 29, 2015 at 01:49 PM · variablenewpointerfieldallocation

Where to allocate class fields in a MonoBehaviour ?

Simple question here - where do you usually allocate class fields in a typical script inheriting from MonoBehaviour (MB) ? Here are few options:

1. Directly in declaration:

 public class GameSessionManager : MonoBehaviour {

     public GameSession gameSession = new GameSession();

     // ...
 }

From a programmer's perspective this is not the best choice, I would rather do it in a constructor, but I am not so sure. However this exact scenario that only covers allocating heap memory with new operator might be an exception and I could do it in MB constructor just fine.

2. Inside Awake() method:

 public class GameSessionManager : MonoBehaviour {

     public GameSession gameSession

     void Awake() {
          gameSession = new GameSession();

          // ...
     }

     // ...
 }
     

this might easily cause troubles when other MB scripts want to set up their shortcut pointers to gameSession object in Awake methods because the order of Awake() calls between scripts is arbitrary. Example, calls in order:

 // 1. shortcut creation inside Awake of some SomeScript
 gs = GameObject.Find("Control").GetComponent("GameSessionManager").gameSession;

 // 2. allocation inside Awake of GameSessionManager
 gameSession = new GameSession();

 // 3. sometime later in SomeScript, causes Exception since this pointer is no longer valid
 int currentScore = gs.score;

3. The third option I can think of is to make it in both Awake() and Start(). I'll just make sure that Awake only covers allocation and Start only covers setting up shortcut pointers, but I feel adding this kind of "hidden logic" to the code is wrong as well.

What do you think, how do you usually do this ?

Comment
Add comment
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

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by nisovin · Jul 29, 2015 at 05:03 PM

It seems like option 3 would be best here. Use Awake() as basically the constructor where you set up the object itself, and Start() as a way to set up references between objects, now that you know that everything is ready.

Another option that might offend your programmer sensibilities, is to make that gameSession variable static. Yes, there's something to be said for strong coding standards and principles and following design patterns. However, there's also something nice about easy, readable code and simplicity. If there's ever only one game session active at a time, having a static variable makes everything so easy.

Comment
Add comment · Show 2 · Share
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 getyour411 · Jul 29, 2015 at 05:23 PM 0
Share

You might also look at a Singleton pattern. I recently had to decide on something along these lines too for my Game$$anonymous$$anager and went with Singleton as it looked like later that would be easier to use with save/Serialization.

avatar image TheLagbringer · Jul 29, 2015 at 06:06 PM 0
Share

Interesting, haven't really thought of making it static. $$anonymous$$akes sense, thanks for the answer. However it definitely looks like the third option is the best. I'll wait a bit before marking this as a correct answer.

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

Can someone tell me whats the difference between these? 1 Answer

Pointer or Copied Value? 1 Answer

Verify if a Component is null 3 Answers

Store Multiple values in one variable 2 Answers

Having trouble with static references. 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