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
1
Question by robinking · Nov 16, 2010 at 01:48 PM · awakedeclaration

What's the difference between code in Awake() and code at the top of the script?

When setting up arrays, variables etc, I generally put setup code outside any function, at the top of the script alongside the variable declarations, instead of in Awake(). What's the difference?

Comment
Add comment · Show 1
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 SisterKy · Jul 28, 2011 at 07:13 PM 0
Share

very nice info, thank you!

cross-reference on closely related topic: assigning variables at the top or in Awake/Start
Greetz, $$anonymous$$y.

3 Replies

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

Answer by duck · Nov 16, 2010 at 05:01 PM

Code outside of any function goes into a special separate function in Javascript (which is hidden from you, but incidentally is called "Main"). This function is called before Start, but not before Awake.

Awake is special in that it behaves similarly to a Constructor in that it is called immediately, and blocks the calling function (although technically it is not the constructor). This means if an object is instantiated at runtime, its Awake code will run straight away, and to completion, before the code which instantiated it is allowed to continue.

Start, on the other hand, is called later - usually after the entire current frame (including every current script's Update function) has finished processing. The hidden "Main" function containing your "code outside of functions" is called in a similar way, at a similar time - after the current frame has completed, but just before Start is called.

These small code snippets should illustrate this for you:

First, a script which allows us to instantiate objects:

var prefab : Transform;

function Update() { if (Input.GetMouseButtonDown(0)) { print("Before instantiating"); Instantiate(prefab,Random.insideUnitSphere*10,Random.rotation); print("After instantiating"); } }

Next, a script placed on the prefab referenced above, which gets instantiated:

print("This is outside of any function, at the top");

function Awake () { print("This is Awake"); }

function Start () { print("This is Start"); }

function Update () { print("This is a frame"); }

print("This is outside of any function, at the bottom");

Now, the order of execution, as shown by our print statements:

  • Before instantiating
  • This is Awake
  • After instantiating
  • This is outside of any function, at the top
  • This is outside of any function, at the bottom
  • This is Start
  • This is a frame
  • This is a frame
  • This is a frame
  • (etc...)

The exception to this is where you declare variables outside of functions. For these, their definition - including any initial value assigned - occurs before Awake, so these values are available to use immediately from within any function.

Hope this helps clarify things!

Comment
Add comment · Show 4 · 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 robinking · Nov 16, 2010 at 06:50 PM 0
Share

Fantastic! Thanks so much - I'm much the wiser now! :)

avatar image tayl0r · Oct 07, 2012 at 12:14 PM 0
Share

I am seeing some weirdness with instantiating prefabs that contain nested children that also have their own custom scripts on them.

Like:

 * PlayingCard [Card.cs]
     !-- Front [Sprite.cs]
     !-- Back [Sprite.cs]

I instantiate PlayingCard. Front runs Sprite Awake(). PlayingCard runs Card Awake(). Back runs Sprite Awake().

Shouldn't the children (front and back) all run their Awake methods before PlayingCard?

avatar image Romano · Feb 18, 2014 at 02:24 AM 0
Share

Thanks for this duck, I was just about to jump out a window.

Just to be contradictory though, in my current project I have a situation where script A can't access the variables at the top of script B in the Start() function - only by instantiating my variables in script B in Awake() (not at the top) can script A read them from Start().

avatar image Tony-Sparrow · Oct 17, 2014 at 04:39 AM 0
Share

thanks you so much

avatar image
1

Answer by Proclyon · Nov 16, 2010 at 02:04 PM

There must be a ton of this question and a ton of answers but here you go:

Awake is called BEFORE start. Start is a place for your initialization:

private int x; private Vector3 left; private bool spelledRight;

void Start() { x = 3; left = Vector3.left; spelledRight = true; }

Awake is for checking if everything is there before the object finishes construction you need all the pieces.

private AnimationClip _ani;

Awake() { if (GetComponent<AnimationClip>() != null) { _ani = GetComponent<AnimationClip>(); } }

There's some special functions aswell

// Mark the PlayerScript as requiring a rigidbody in the game object. @script RequireComponent(Rigidbody)

function FixedUpdate() { rigidbody.AddForce(Vector3.up); }

C# Example:

[RequireComponent (typeof (Rigidbody))] class PlayerScript : MonoBehaviour { void FixedUpdate() { rigidbody.AddForce(Vector3.up); } }

PERSONAL RULE OF THUMB:

You check if it exists at all You assign whatever exists You don't EVER use anything untested or unchecked (Not double enough)

Fail any combination of the three and u risk serious crashing and headaches.

EDIT 11/16/2010 - 15:06

Oh and one more thing, please remember that putting everything of init in the Start is a bit of extra typing and may risk getting strange 0 values of you forget something. Why it's a great idea to do it all there? Well you may end multiclassing and/or multistructing. It keeps it all in a good logical spot. So is it worth it ? Up to you, just respect the Awake and look at start as a spot for inits.

I might just be totally missing the point of the Start method though, I have little evidence to back this up except Awake.

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 robinking · Nov 16, 2010 at 03:12 PM 0
Share

I know the difference between Start and Awake... was asking about code outside of ANY function, put with var declarations.

avatar image Proclyon · Nov 16, 2010 at 06:23 PM 0
Share

$$anonymous$$y bad, misinterpreted your question. I just read ducks post below and that should answer your question much better. If so don't forget flagging it as the accepted answer :)

avatar image robinking · Nov 16, 2010 at 06:47 PM 0
Share

Cool, thanks!:)

avatar image
0

Answer by Loius · Nov 16, 2010 at 03:34 PM

Code outside any function runs after Awake (but before Start).

Initializations, however, run before Awake if they're not in a function.

So you can have, for example,

var x : int = 7; var y : float = 0.5;

function Awake() { print( x + "; " + y ); }

And that'll print "7; 0.5".

But if you use

var y : float = 0.5;
y += 1;

y won't be equal to 1.5 until after Awake.

There's no guarantee as far as which script runs first, just like Awake, but all objects will run their "outside" code after everything runs Awake.

Also, code outside functions does not fall out of scope, since every function is in a sub-block of the block the code is in.

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 duck ♦♦ · Nov 16, 2010 at 05:12 PM 2
Share

No, code outside of functions actually runs after Awake. However variables declared outside of functions (as you illustrated) get their declared initial values before Awake is called. This is different compared with actually putting functional code outside of your functions.

avatar image Loius · Nov 17, 2010 at 03:12 AM 0
Share

I was sure I had some of my outside code run before awake, but I just tested it and you're right. I must have just been using initializations before. I've edited my post so nobody tries to use the wrong info; thanks!

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

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Do I have to check for null value before assigning a variable in Awake()? 1 Answer

loading elements on startup 2 Answers

Is there a way to ensure Awake is called in Unit tests? 2 Answers

How to import the object from server to unity 2 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