Quantcast
Channel: Answers for "What's the difference between code in Awake() and code at the top of the script?"
Viewing all articles
Browse latest Browse all 6

Answer by Proclyon

$
0
0

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.


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>