-1

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>()
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
filgas08
  • 51
  • 7
  • What's the reason for the downvote? The question seems fairly clear, even if the subject line may be a bit ill-chosen. – O. R. Mapper Oct 03 '21 at 17:52
  • that code shouldn't even compile at all ... you can not use instance methods to initialize a field on declaration because this would happen in a static context .. even less if it is about a static field ... – derHugo Oct 03 '21 at 17:55
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Jonathan Oct 03 '21 at 17:57
  • 1
    @derHugo: While that is true, that seems at best tangential to the problem in focus (which appears to be the behaviour of `GetComponent`) and the most appropriate reaction would probably be a comment asking for clarification rather than a comment-less downvote. YMMV. – O. R. Mapper Oct 03 '21 at 17:57
  • @O.R.Mapper I think downvotes are fully understandable if the posted code doesn't even compile .. so how should we even know what exactly OP is asking? [`GetComponent`](https://docs.unity3d.com/ScriptReference/Component.GetComponent.html) is well documented and any misbehaviour most probably a user mistake .. which again we can't provide any helpful answer for if we don't even see the actual usage .. – derHugo Oct 03 '21 at 18:01

1 Answers1

1

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.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114