Is it possible to call a function when starting a Unity program?

I was wondering if there is a way in Unity, when I run my program on stage, it starts the function first, I have to add that I want this one function to work no matter what area I am in. a simple start function will not allow it. Not sure if this is possible in Unity?

public void ProgramBegins()
{
    //FIRES FIRST ON ANY SCENE
    //DO STUFF
}
+4
source share
3 answers

RuntimeInitializeOnLoadMethodAttribute can help you :)

using UnityEngine;

class MyClass
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void OnBeforeSceneLoadRuntimeMethod()
    {
        Debug.Log("Before scene loaded");
    }
}
+12
source

Here you can find the execution order of all functions in unity: http://docs.unity3d.com/Manual/ExecutionOrder.html

Awake - , . GameObject script, Awake. , , .

, . GameObject , , .

+3

prefab _AppStartup, , script AppStartup. AppStartup , , @maZZZu.

AppStartup :

  • , .
  • ,

    public class AppStartup : MonoBehaviour 
    {
        const int bootSceneNo = 0;
    
        public static bool veryFirstCallInApp =  true;
    
        void Awake ()
        {
            if (veryFirstCallInApp) {
                ProgramBegins ();
                if (Application.loadedLevel != bootSceneNo) {
                    // not the right scene, load boot scene and CU later
                    Application.LoadLevel (bootSceneNo);
                    // return as this scene will be destroyed now
                    return;
                } else {
                    // boot scene stuff goes here
                }
            } else {
                // stuff that must not be done in very first initialisation but afterwards
            }
            InitialiseScene ();
            veryFirstCallInApp = false;
            DestroyObject (gameObject);
        }
    
        void ProgramBegins()
        {
            // code executed only once when the app is started
        }
    
        void InitialiseScene ()
        {
            // code to initialise scene
        }
    }
    

So all you have to do is drag this assembly into each scene manually and give it -100 or something else in the order the script runs. Especially when the project grows and relies on a predetermined flow of the scene, it will save you a lot of time and hassle.

+2
source

All Articles