- Home /
MonoBehaviour methods in non-MonoBehaviour class
I noticed that in non-MonoBehaviour class, I can still use some of MonoBehaviour methods. So where I wrote in MonoBehaviour class, Instantiate(...)
, in non-MonoBehaviour class I can update this like of code as MonoBehaviour.Instantiate(...)
and it will work perfectly. I haven't found a single problem with this so far. This however applies for static methods of MonoBehaviour class. In case of non-static methods, like StartCorotuine(...)
, code like MonoBehaviour.StartCorotuine(...)
won't work.
Despite this works fine in all my testing so far, I noticed that nobody mentioned code like MonoBehaviour.Instantiate(...)
and makes me believe that there is some horrible problem with this, that I am not able to see yet.
I wish to use non-MonoBehaviour classes as library-like classes. Classes full of various utility methods of the same context. Like EffectsTools class, LevelTools class, etc. And exactly in these classes, I never saw a problem with direct use of MonoBehaviour static methods in the way I described.
I also noticed that for example, Instantiate or Destroy can also be coded as GameObject.Instantiate(...)
or GameObject.Destroy(...)
in non-MonoBehaviour class as well. It also works fine. Perhaps this is better, safer idea?
Answer by Pangamini · Jan 29, 2019 at 01:04 PM
Instantiate is a static method of UnityEngine.Object class, from which MonoBehaviour, GameObject and all built-in unity asset types derive. There's absolutely no problem with calling them from anywhere (on the main thread). StartCorotuine is a method of a monoBehaviour instance (it's not static). It can still be called from outside the MonoBehaviour derived class, but on a specific instance, for example
class MyNonBehaviourClass
{
public MonoBehaviour behaviour;
void StartRotine()
{
behaviour.StartCoroutine( .... );
}
}
Well summarized :). I tend to write too much. This contains all information required.
Good to know there's no problem :)
As for StartCoroutine()
specifically, this is quite interesting. $$anonymous$$y impression from searching was that it couldn't be really done outside of $$anonymous$$onoBehaviour. I didn't know at all that it could work this way, thanks! :)
There's no black magic used in Unity. StartCoroutine() is just a public method
Your answer
Follow this Question
Related Questions
Is it possible for a non-MonoBehaviour class to use built-in functions? 1 Answer
Trying to run 5 instances of a static method at once to do an action, probably a dumb thing to do? 0 Answers
Can a static class have an Update() function which Unity calls automatically? 1 Answer
[SOLVED]From superior script to subordinate script 1 Answer
Static class member for offset 1 Answer