- Home /
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.
Example:
print ("Game has loaded");
//call another script to start playing music for the menu screen var externalScript = gameObject.GetComponent(musicControl); externalScript.startPlayingIntroMusic();
//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!
Answer by Mike 3 · Jul 27, 2010 at 09:32 PM
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:
http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.html
Answer by fherbst · Jul 27, 2010 at 09:33 PM
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.");
}
Thanks. That's useful and good to know. You think this would be where most examples or tutorials start but they dive straight in to character animation and physics ins$$anonymous$$d! Am sure I tried Start() and it didn't work but maybe the result of another error. I checked the hello world example in unity scripting reference thinking that would be a function that ran once -The example attaches it to an update so it loops!
Looks like most of my errors came from not understanding the term STATIC. Static functions are what I need, though I did not know what I was looking for.
turns out I also wrote start() ins$$anonymous$$d of Start() !!
Answer by Deeweext · Jun 11, 2013 at 11:38 AM
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.
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Inverse function of OnTriggerStay? 3 Answers
Script to teleport player (Beginner here) 0 Answers
Static function and variables error 2 Answers