1
\$\begingroup\$

I want to run a function once per main loop iterator but I don't want to add this as a script to a game object in my scene. This is something that should always run no matter what scene and making people include it into every scene on a game object would cause issues because I'll/people will forget. Is there any hooks into the main loop where I can tell unity to run this function once per loop for the entire game not just per scene?

\$\endgroup\$
  • \$\begingroup\$ Every script that need run a update loop need derive from MonoBehavior what you asking for is impossible without script sorry \$\endgroup\$ – buffalo94 May 5 '18 at 17:02
2
\$\begingroup\$

You can create directly from the script a gameobject as a singleton marked as DontDestroyOnLoad: this way, the gameobject will be persistent during the entire duration of the runtime.

Note that you have to create a game object in the first scene loaded, or you won't be able to execute the Update method. With this script, however, you don't need to physically create the game object in the editor, it's created automatically by the script itself only at runtime.

This is the code:

using UnityEngine;

public class AutoSingletonScript : MonoBehaviour {
    [RuntimeInitializeOnLoadMethod]
    private static void Initialization() {
        if (FindObjectOfType<AutoSingletonScript>() != null)
            return;
        var instance = new GameObject { name = "AutoSingleton" };
        instance.AddComponent<AutoSingletonScript>();
        DontDestroyOnLoad(instance);
    }

    private void Update() {
        // Do Stuff
    }
}
\$\endgroup\$
  • \$\begingroup\$ That's brilliant! Thank you very much. This really is like a hook into the main loop! \$\endgroup\$ – user441521 May 5 '18 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.