Get an instance of a class that aren't attached to any gameObject.

I just want to that is there is a possible way for me to get an instance of a class that aren’t attached to any gameObject.

Thank You Very Much!

var foo = new MyClass();

In this case, “foo” is the reference.

–Eric

If it’s a class that inherits from monobehaviour:

public class MyNewScript : MonoBehaviour { }

The new keyword won’t work inside of another class that also has that same inheritance:

public class MyOtherNewScript : MonoBehaviour {
private MyNewScript myNewScript;
Start() {
   myNewScript = new MyNewScript();
}
 }

That won’t work above, so instead you use AddComponent:

public class MyOtherNewScript : MonoBehaviour {
private MyNewScript myNewScript;
Start() {
   myNewScript = this.gameObject.AddComponent<MyNewScript>();
}
}

And it will attach that script as an instance to your game object.

1 Like

If you’re only using a single instance of a class that inherits from Monobehaviour, a singleton style pattern might help. You would need to add this to the script that you want an instance of that isn’t attached to a gameobject.

public class MyScript : MonoBehaviour
{
    private static MyScript myScript;
    public static MyScript Instance ()
    {
        if(!myScript) {
            myScript = FindObjectOfType (typeof(MyScript)) as MyScript;
        }
        return myScript;
    }
}

…it can be called as follows

MyScript.Instance().SomeMember;
1 Like

Thank you everyone! I don’t quite understand the singleton style above. So the conclusion is the only way to get instance is to put the script into the gameObject and get Component from that gameObject right?

Much appreciate!