Hi. I’m pretty new to scripting and I realized while I was creating my state machine that my StateMachine class is inheriting from ScriptableObject (because I don’t want it to be attached to a particular gameobject). And my PlayerStateMachine class is inheriting from the StateMachine class. I wanted to know if there was a way to call the Update() function even if that class is not inheriting from MonoBehaviour. Any help would be appreciated.
GravStateMachine.cs is my StateMachine class
PlayerStateMachine.cs is my PlayerStateMachine class
If you’re going to have a singleton MonoBehaviour, it’s a lot easier to have it be lazy:
public class UpdateCaller : MonoBehaviour {
private static UpdateCaller instance;
public static void AddUpdateCallback(Action updateMethod) {
if (instance == null) {
instance = new GameObject("[Update Caller]").AddComponent<UpdateCaller>();
}
instance.updateCallback += updateMethod;
}
private Action updateCallback;
private void Update() {
updateCallback();
}
}
This means that you don’t have to remember to add a script to every scene you use. If your prefabs are relying on that UpdateCaller existing, that will make testing those prefabs a lot easier too.
As an added bonus, you get rid of the null-check. I haven’t added any unsubscribe functionality, but you should add that if you need it (if your ScriptableObjects that use this ever get destroyed). You’ll also have to make decisions about if the UpdateCaller should be set to DontDestroyOnLoad or not, depending on if your Scriptables live between scenes.