I want initialize monobehaviour class from static class but i am getting warning.
“You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all”
If this will be in non static class i will go with
MyScript script = FindObjectOfType<MyScript>();
Currently i am using this but getting this warningMyScript script = new MyScript();
But how can i do this from static class and dont get this warrning?
Thanks for help.My code is working but i dont like this warning.
It will allow you to execute the first line of code you posted from a static class. As @PraetorBlue said, you can not create it with “new”. So you have two options.
A) Find the existing object (Find… et all) and reference it in your static class. Which is the solution I posted.
B) Another option would be to create a new empty GameObject (new GameObject) and then use AddComponent() to create your script on it. Though usually people use Prefabs to do this. This is what PraetorBlue was talking about.
I have one non mono behaviour class what managing my DB - SqlManager
In this script iam trying to create event what will trigger when value in my DB is updated.
Then in my second MONOBEHAVIOUR class i want capture this event and i want update UI values, i post my codes.
Thanks for help
If i make both scripts monobehaviour and if i replace MenuUI mUI = new MenuUI(); for MenuUI mUI = FindObject… and add SqlManager to GO then it is working but i dont want to have my SqlManager script as monobehaviour
Doesn’t need to be static… just make it a singleton with an instance initializer (kinda how Vryken is doing above) and the first time you use it, everything will get set up, because by that time, Unity is truly up and running and you can safely call .AddComponent() to create your Monobehavior.
My apologies, not sure why I inherited from MonoBehaviour there (typed it from memory on my tablet ). I fixed the error above.
If I got you right then SQLManager is NOT a MonoBehaviour. You could make it a singleton and then request it from whichever class needs it (MonoBehaviour or not).
Also, I saw in your ui that you subscribe to the event with += in the Update() of your MonoBehaviour. You better move this to Awake() or OnEnable() or else it will subscribe anew in every frame, which I guess is not what you intended.
Thanks for your answers, it helped however i like to know one more thing.
I have both scripts conected now Static class to Monobehaviour it is fine but i “FindingObjectOfType” each time i call this function and i dont like it. Is here some way how can i initilize this on start in static class?