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
3
Question by AmazingDeveloper2 · Feb 23, 2015 at 10:41 PM · initialization

Where should I initialize variables?

Is it a big difference between initializing variable in the beginning of the script - where it was declared, or inside Start() function? In both cases variable will be initialized, when script start working.

Is it just a good tone - to initialize variables inside Start()?

 int x = 5;

or

 int x;
 
 void Start() {
     x = 5;
 }
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

4 Replies

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

Answer by siaran · Feb 23, 2015 at 11:07 PM

Well, the best answer that I have here is: It depends.

If you have a public variable that you initialize at the start of the script, it will set itself to what you initialized it to in the editor, but then if you change that in the editor, it will have the changed value.

If you initialize variables in Start() you cannot change them in the editor, accidentally or otherwise. (Well, you can - but when you start playing they will always be set to the values you put in your Start() method).

Or in some cases you might even want to initialize them in Awake() (which is an initialize method that takes place before Start() ).

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

Answer by Kiwasi · Feb 23, 2015 at 11:04 PM

There are more options then proposed for initialisation. They include:

At declaration - Use this to set up a default value. Note that these values can be overridden by the values typed in the inspector. Useful for data you want serialised that needs a default value. For data not serialised there is little difference between initialising here and initialising in any of the built in functions.

Via the inspector - For serialisable types you can mark these as [SerialiseFeild] and initialise them via the inspector. You can also initialise public variables via the inspector, but this can lead to bad coding practice

Awake - Use this for all internal initialisation. Set up all of the internal class variables. Set up references to other classes, but don't access the other classes yet.

Start - Use this for all external initialisation. Anything that relies on the variables of other classes should be done here.

OnEnable - Use this as a "reset" for any variables that need to be cleared before reusing the object. Great for object pools and the like.

Edit: Improved answer based on comments

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 Bonfire-Boy · Feb 23, 2015 at 11:42 PM 0
Share

There's a massive difference. If you only do it in the declaration then you can change its starting value for an instance or prefab in the inspector. If you set it in Start() then you can't (as per Siaran's answer)

avatar image Kiwasi · Feb 24, 2015 at 10:07 PM 0
Share

@Bonfire Boy. Valid point. Have updated my answer to reflect this.

In fairness the OP code examples uses private, nonserialised variables, so serialisation does not matter for this specific case. But its true of the general case.

avatar image
0

Answer by ematsuno · Dec 09, 2019 at 12:33 AM

You can Initialize the variables before the inspector is opened by calling the Awake() function from the Editor. You'll need to define the Initialize() method inside your Monobehavior and execute it from the editor as below using this example. ( you can do the commented out way, which may be better in some cases)

 using System.Collections;
 using UnityEngine;
 using UnityEditor;
 //must be placed inside the editor folder
    [CustomEditor(typeof(<myComponent>)]
     public class myCustomComponentEditor : Editor 
     {
      private void Awake()
         {
             <myComponent> myTarget = target as <myComponent>;
              myTarget.Initialize();  // initialize your variables in your component
         //myTarget.myInt=3;
          }
 }



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

Answer by Jaakk0S · Sep 22, 2021 at 06:38 PM

I have a public variable in a MonoBehaviour that I'm reading in OnCollisionStay(). No matter if I initialize it in the declaration or Awake() or Start(), when OnCollisionStay() is called the value is initialized to the one in the editor field. Also using [HideInInspector] doesn't help.

I found the only way to initialize it in the code is to make the variable private and to add a setter.

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

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

23 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Initialising List array for use in a custom Editor 1 Answer

Finding a gameobject in a level that has not been loaded 1 Answer

vector2D Array initialization not working. 3 Answers

Init code goes to Null unknow reason 2 Answers

Attempting to change AnimatorController during Runtime 0 Answers


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