- Home /
Update() in non-component script?
I'm building a custom input manager since Unity's default one does not satisfy me. I built a custom static class in C# to access all of the set actions, but I need it to check the devices for input constantly.
How to get a function that is executed once per frame in a static class?
Alternatively, how to get a MonoBehaviour-derived static class to execute an update function withot having been linked to a GameObject?
Answer by Mike 3 · Jun 28, 2010 at 01:25 PM
You can't - at some point, you have to have a monobehaviour in the scene to propagate the event
The easiest way is to create a simple script which calls an event in your static class, which other classes register their delegates to
e.g.
void Update() { YourStaticClass.Update(); }
//in YourStaticClass:
delegate void UpdatingEventHandler(); public event UpdatingEventHandler Updating;
void Update() { if (Updating != null) Updating(); }
//in a class wanting to listen to the event:
YourStaticClass.Updating += OnUpdate; //this goes anywhere, a constructor maybe
void OnUpdate() { //your code }
But the $$anonymous$$onoBehaviour has to be linked to some object in the scene?
@Ferdil, it can be an Empty GameObject, which won't be visible. Or anything else handy, like a Camera.
But why use events/delegates? Wouldn't a simple function call be enough?
Then you'd have to call every single function which needed to be drawn. Say you have 50 classes which want the GUI event - you'd have to add all of them into the code. With the event, you just register a delegate from the class which wants it and you're done.
Answer by vargonian · Dec 28, 2013 at 09:26 AM
Another option is that your custom class an implement an interface that you define called IUpdateable (or something like that) which contains a single method, Update(float dt). You can then keep track of these IUpdateables in whatever way suits you and have their Update methods called during a MonoBehavior's Update in your scene. So, if you have a CoreGameBehavior script or something, its Update method might look like this:
foreach (IUpdateable updateable in this.updateables)
{
updateable.Update(Time.smoothDeltaTime);
}
This has a benefit in that your IUpdateable interface need not depend on any Unity libraries.
This is of course a simple version; your needs may vary.
Answer by Ward Dewaele · Jul 09, 2010 at 02:35 AM
i was doing the same as you - feel free to check my custom input manager out. I released it for free.
Currently it can do this : - read input from joystick buttons and (up to 4) axis - read input from mouse buttons and axis - read input from all keys from the keyboard - save the configuration to PlayerPrefs (and ofcourse load them back) - reset to default keys (which u can setup in the inspector)
Visually im not an artist so u have to pimp it up yourself. This will work in both standalone and webbuilds. Hope this satisfy you - the link is HERE