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 SisterKy · Dec 08, 2009 at 03:29 PM · optimizationscriptingbasicsawakedeclarationexecution-order

Difference of assigning a variable outside any function, in Awake or in Start?

Is

var myVariable = 5;

short for

var myVariable;
function Awake() 
{
   myVariable = 5;
}

? Or is it rather

var myVariable;
function Start() 
{
   myVariable = 5;
}

?

So do the public Variable-Declarations get called only if the script-instance is enabled (-> the same as Start) or are they declared anyway (-> the same as Awake)?

And are there any other merits or flaws of the short or the long versions to be aware of?

Thanks & Greetz, Ky.

Edit 28/07/2011: just found this closely related question
And more on execution-order

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

3 Replies

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

Answer by duck · Dec 08, 2009 at 04:15 PM

In your specific example, the answer is actually neither. It gets compiled to this

public class YourScriptName extends MonoBehaviour { public var myVariable : int = 5;

 // ...then any other functions follow...

}

However, this can differ if your var is initialised as something which cannot be executed outside of a function. In these cases, the value is assigned in the classes constructor. For example, this:

var myVariable = transform.position;

Will be compiled to this:

public class YourScriptName extends MonoBehaviour { public var myVariable : Vector3;

 public YourScriptName()
 {
     myVariable = transform.position;
 }

 // ...then any other functions follow...

}

The class constructor is called during the process of instantiating the class, so these are assigned even before Awake() is called.

"are there any other merits or flaws of the short or the long versions to be aware of?"

In general, it's good to be aware of what the compiler is doing for you behind the scenes, because it can help you understand the system that you're working with better, and ultimately allows you to write more efficient code. There is a little more detail in "Head First into Unity with Javascript" on the wiki, under the heading "Each .js File Implements a Class.

Comment
Add comment · Show 3 · 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 jashan · Dec 09, 2009 at 08:06 AM 0
Share

Are you sure this gets compiled into the constructor? Since using the constructor is not recommended with $$anonymous$$onoBehaviours for good reasons I don't think this is the case (in particular for the second example); that's what Awake() is for (initialization). From the recommendations for writing scripts in C#, I would conclude that in fact, javascript code outside of functions that needs to be executed goes into Awake(), and member variable declarations go into the class body; see also: http://unity3d.com/support/documentation/ScriptReference/index.Writing_Scripts_in_Csharp.html

avatar image duck ♦♦ · Dec 09, 2009 at 11:40 AM 0
Share

Yup, sure. I decompiled an test project myself before adding this answer, to make sure.

avatar image SisterKy · Dec 09, 2009 at 12:45 PM 0
Share

Thanks a lot, very helpful! =) Yes, that's what I'm trying, to get behind the scenes. Just started Unity last Saturday so still a long way to go and few clues where to start best... I'll definitly look into your link. =)

avatar image
2

Answer by Stelimar · Dec 08, 2009 at 03:32 PM

I'm pretty certain they get declared anyways. The "short version" will have the values set BEFORE any functions (including Start or Awake) are called. In addition, if you change the value of myVariable in the editor, with the "long version" the value will get overridden.

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
1

Answer by jashan · Dec 09, 2009 at 08:19 AM

As Duck pointed out, the given example goes into the class body. In other words: Variable declarations don't go into any method (methods are what is known as "functions" in JavaScript; in object oriented languages, "methods" is the more common term).

The reason variable declarations outside a "function" in JavaScript go into the class body is because they are actually member variables with object scope, in other words: The variables holding the "state" or "data" of the object. Were they put into a method, they would only be accessible inside that method ("method scope"). This also becomes obvious when you look at such scripts in the Unity editor: Member variables are exposed in the property inspector. You can change them, and those changed values will be available in your scripts.

In other words: One thing that Unity does behind the scenes is serialize and deserialize the values you've entered in the editor.

Executable code you have in a JavaScript file, outside of functions, is put into a Main() method (with the exception that Duck pointed out), so this:

var myVariable = 5;

for (var i = 0; i < 5; i++) { myVariable++; }

Is compiled into this:

[Serializable] public class TestScript : MonoBehaviour {

 public int myVariable = 5;

 public void Main() {
     for (int i = 0; i &lt; 5; i++) {
         this.myVariable++;
     }
 }

}

The Main() method is executed after Awake() and before Start().

You can deduce some of this from Overview: Writing Scripts in C#, the rest can be found out with a decompiler, like .NET Reflector, and a simple test-class (which prints to Debug from the different methods).

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

1 Person is following this question.

avatar image

Related Questions

'function Update' vs 'function Start {while(true)}'? 3 Answers

The Merits and Pitfalls of declaring multiple Classes in one Script? 1 Answer

What is the general use of Awake(), Start(), Update(), FixedUpdate(), LateUpdate()? 7 Answers

OnEnable called before Awake 2 Answers

What's the difference between code in Awake() and code at the top of the script? 3 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