running code outside of update!

Trying to run some basic code to control my game application. According to unity scripting reference all code has to be run inside and Update function. Meaning it will run every frame -and it has to be attached to an object!!

How do I get some code just to run once? Outside of any function when my game starts. Surely everyone needs a script like this somewhere in their project?

I really need to know where to put it. Putting the code outside of an update function just results in lots of errors.


print ("Game has loaded");

//call another script to start playing music for the menu screen
var externalScript = gameObject.GetComponent(musicControl);

//declare global variable lives = 10;
var lives = 10;

Really want to do some good stuff in unity, but it's such a slow process. Every time I start I spend hours just trying to get the most simplest of scripts to work. Then it gets late and I have to leave it again!

Use the Start or Awake functions

Also - there are lots of other automatically called functions, not just Update - I'm not sure where you got that from

You can see the majority of the Overridable Functions section here:

You can use the `Start()` or `Awake()` functions. And put that script on some GameObject in your scene. Most people use something like a Master gameObject which handles all the game logic and so forth (as far as I know).

So, use something like this:

function Start()
  // Do-A-Lot-Of-Stuff
  // ...
  print("Game started.");

You read a tutorial before asking questions. I’m sure there is no where it says all code has to run inside an update function.

~ Old question bumped; Valid answer posted.