I recently started investigating Unity. So far, it seems that scripts can only be attached to game objects, which means objects are more or less tied to a single scene.
Is it possible to execute code when the game starts? If so, how could objects created at that point be accessed by scripts that are tied to game objects?
Thanks beforehand. 
When the game starts, the first scene is automatically loaded an all monobehaviours within it get their Awake called.
so if you would want to have a first “primary” point of starting you would ensure that the first scene has a single monobehaviour in and thats the one that you want to do something.
Before that point there is no access to anything and if unity is running there is always a scene and there will always be game objects at least if you wanted to do anything with any kind of media at all (which one would assume or you wouldn’t use unity :))
Ok, that’s kind of what I expected. So I assume that, for persistent objects, I’d have to use static objects / singletons, which I would instantiate in the first scene. These objects do persist across different scenes, right?
If you use DontDestroyOnLoad, yes.
You can have scripts not attached to game objects, as long as they aren’t Monobehaviours. These can’t “run” by themselves, though, and are usually used for things like static functions. You use prefabs for objects you want to instantiate in multiple scenes.
–Eric
Ah, ok, thanks. I was wondering whether Unity would start up a new interpreter or VM instance per scene, but it just cleans up game objects and the MonoBehaviors attached to them. Makes sense.
But will static objects / singletons (anything that’s not a member of a MonoBehaviour) persist regardless? Obviously, they’ll need to be instantiated by a MonoBehaviour, but from that point on they’re live until the game terminates, right?
If you’re working in C# and you use a class that is not derived from MonoBehaviour, you can use a static initialiser to set up persistent values:-
public class MyScript {
static int myVal;
static MyScript() {
myVal = 19;
}
}
It is defined like a constructor, except qualified with “static” and it can only use static variables.
I was thinking towards the following, although both should work just fine:
public class PersistentObject
{
public static PersistentObject instance = new PersistentObject();
public string name;
public PersistentObject()
{
name = "Persistent object";
Debug.Log(name);
}
}
However, I noticed that in both cases the object is only created the first time it’s referenced from within an active MonoBehaviour. So unless I somehow access PersistentObject.instance, it is never created. So that’s something to keep in mind.
Either way, it’s good to know that once it does exist, it will persist. Thanks for the help. 