- Home /
Run Script From Level to Level
Hi. I'm about 2 weeks new into Unity. This question is similar to this one:
http://answers.unity3d.com/questions/9105/getting-a-script-to-run-without-attaching-it-to-a-gameobject
but not forcing people to read that, suppose I've a game with 2 or more levels. As a player goes from level to level, I need some way to execute the same script at the start of every level. This script isn't going to be seen in-game but just does things like read in data from files. A way I thought of is to basically just create a GameObject, attach my script, and in the Awake method I do:
void Awake()
{
...
DontDestroyOnLoad(transform.gameObject);
...
}
so that way, my GameObject persists from level to level, which contains my actual script that I need to run from level to level. Is this a decent way? Seems a bit of a hack because the problem with the above is that if I load the same level n number of times, it creates n instances of the GameObject, so I'd have to do a check for that, so that is why this seems a bit of a hack to do it like this. Another way I thought of is to merely statically create a GameObject for every level and attach my script, but that's unelegant, but it seems better, so as to avoid a possible memory leak.
DDOL is DontDestroyOnLoad. He was asking if you've tired DontDestroyOnLoad(this)
Answer by zannghast · Nov 03, 2010 at 05:38 AM
What you could do is load the gameObject in a scene that is less likely to be "loaded again". Say for example the start-up screen. Then call DontDestroyOnLoad on that object in said scene.
Alternatively, have you tried experimenting with singletons?
Hi. Thanks for the input. Hadn't thought of loading it up on a start-up screen; sounds like a great idea; it's probably what I'll do. I like the Singleton suggestion, but if it'll still require the creation of a GameObject for every level solely for containing a script or maintain a persistent GameObject across levels, then I think your 1st suggestion is preferred for my needs. Thanks for the input, and I'm sure I'll have lots of questions about other things.