Same OnEnable()/OnDisable() on multiple scripts? Calling same method name from one script

Hi everyone,

so I have multile scripts that have a reset() method
and I call a reset() method from my main script, which then basically calls the reset method from all other scripts.

What I’m doing up to now, is this:

ExampleA[] p = FindObjectsByType<ExampleA>(FindObjectsSortMode.None);
foreach (ExampleA p2 in p) {
    p2.Reset();
}
     
ExampleB[] s = FindObjectsByType<ExampleB>(FindObjectsSortMode.None);
foreach (ExampleB s2 in s) {
    s2.Reset();
}

//[,,,]

Now I came up with the idea, to add all the reset() in a delegate OnEnable() and subtract them OnDisable() and then call that delegate instead, which of course makes my code way shorter.

However, if I do so, I’d now need to add OnEnable()/OnDisable() to each of that script.

Does anyone know a good solution for this case?

Thanks in advance

You could do it by an interface that more than one class expresses, such as an IResettable

I don’t think Unity’s find stuff works with interfaces (yet?) but the Get Component does, so you could iterate root GameObjects and ask each one GetComponentsInChildren() with your interface to find ALL that have IResettable.

More reading:

Using Interfaces in Unity3D:

Check Youtube for other tutorials about interfaces and working in Unity3D. It’s a pretty powerful combination.

1 Like

This is a case of there being many ways all with various pros and cons.

One option is to subscribe/unsubscribe to a manager that resets these objects at specific points.

Another is to just do a full sweet with FindObjectsOfType<T> and reset every hit.

Perhaps a combination of both. I think most of us have our own internal API for this kind of stuff.

1 Like