- Home /
Getting a script to run without attaching it to a GameObject
I was wondering if there was a way to run a Manager / Singleton class when my game starts without attaching it to any gameObject. I need this class to hold references to my current camera and other such objects which I'd like to access from a variety of different scenarios.
Answer by duck · Apr 30, 2010 at 04:42 PM
You need at least one script attached to a gameobject somwhere in your scene.
However you can use that script's Start() function as a hook from which to instantiate any number of your own classes which themselves aren't attached to a GameObject.
If you're going to create new instances like this, make sure that they don't inherit from MonoBehaviour, since the way that MonoBehaviour works makes some assumptions that it is attached to a GameObject.
So the rule for creating instances of scripts at runtime are:
For MonoBehaviours, always use:
gameObject.AddComponent(MyScript)
For non-MonoBehaviours, always use:
new MyScript();
In summary, you can have scripts running which aren't attached to GameObjects, but you can't get scripts running in the first place without at least one attached to a GameObject, to "kick things off".
So, in theory, I could just add a empty gameObject and attach my script to that?
Yeah, thats right. Im creating always a "Controller"-script and a attach that to an empty gameobject. Theres my whole functionality for key presses, loading scenes, objects etc. Here you can access other gameobjects/components, too..
Answer by JacobK · Sep 27, 2017 at 01:25 PM
This is possible since Unity 5 or so, using [RuntimeInitializeOnLoadMethod]
See: https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
I'm pretty experienced with Unity, yet this is the first time I've heard of this (see$$anonymous$$gly) extremely useful attribute! If this works as expected, it is amazing!
Answer by yeahdixon · May 21, 2014 at 10:07 PM
IN addition you can have a singleton class that is not a monobehavior, that has links to game object in your scene. You can Call : AppState.Instance().goGame=this.gameObject;
and can be called from within empty game object script.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AppState {
public static AppState _instance = null;
//holder for reference
;
public GameObject goGame;
public AppState() {
Debug.Log("constructor ");
}
/* singleton */
public static AppState Instance() {
if (_instance==null)
{
_instance=new AppState() ;
}
return _instance;
}
}
Answer by UnitedVector · Aug 26, 2018 at 03:21 AM
Make your class extend UnityEngine.ScriptableObject, then use the ScriptableObject.Awake() function to do what you want
Just been testing that. -- It's doesn't work on it's own if it's just a script in your assets.
Your answer
