I have an instance of a class and it is null, how can I solve this?
It is a monobehavior assigned to an object.
static Myclass instance = GetComponent<Myclass>()
I have an instance of a class and it is null, how can I solve this?
It is a monobehavior assigned to an object.
static Myclass instance = GetComponent<Myclass>()
If GetComponent
returns null
, then that is because there is no component of the specified type attached to your GameObject
. From the GetComponent
docs (emphasis by myself):
Returns the component of Type
type
if the game object has one attached, null if it doesn't.
In other words, GetComponent
will not automatically create the component if none is found.
Once you have discovered that there is no component of the specified type available, you can use the AddComponent<T>
method to create one instead.