Sorry about that. As far as I remember FindObjectOfType
can’t do interfaces but GetComponents
can and so I get them mixed up.
Since the reset won’t happen very often you could use Linq
foreach(var resetable in FindObjectsOfType<MonoBehaviour>().OfType<IResetable>())
{
resetable.Reset();
}
It gets all the MonoBehaviours
and then filters them on the interface. May be a little expensive but like I said, it doesn’t happen every frame so it should be fine.
That’s pretty much what’s happening in the code above. Yes, it may be performance heavy (especially in a scene with lots and lots of components) but it doesn’t happen often so it shouldn’t be an issue. The - probably better - alternative is to use the events @Brian_Trotter mentioned. With that, only the components that care (which would be the same ones you would’ve implemented the interface on) will respond and there’s no need to look at any components that have nothing to do with resetting.
If you insist on using the code above and it does cause a noticeable drop in frames you could run a coroutine that would fade to black, run the resets over multiple frames and then fade in again. Something like
private IEnumerator ResetSceneRoutine()
{
yield return FadeToBlack(); // Assumption that we have a Coroutine to fade
var resetCount = 0; // count resets so we don't yield after every single reset
var maxResetsPerFrame = 10; // Magic number - should be configurable
foreach(var resetable in FindObjectsOfType<MonoBehaviour>().OfType<IResetable>())
{
resetable.Reset();
resetCount++;
if (resetCount == maxResetsPerFrame)
{
yield return null;
resetCount = 0;
}
}
yield return FadeIn(); // Assumption that we have a Coroutine to fade
}
Again, I don’t know if this will work. I write code in-post all the time and make mistakes