- Home /
How to call an implemented custom Interface
Hello. I'm interested in implementing a custom and simple interface to facilitate saving and loading my game. What I want is something like this:
public interface ISavable
{
void OnSave();
}
And use it like this:
public class MyObject : MonoBehaviour, ISavable
{
public void OnSave()
{
//Save variables
}
}
public class MyOtherObject : MonoBehaviour, ISavable
{
public void OnSave()
{
//Save different variables
}
}
How would you call this OnSave() on every class that implements ISavable?
I was doing it with a custom event system, but I'd love to know how to implement it this way and make it cleaner, without having to use listeners on OnEnable and OnDisable on every single class I want variables to be saved.
Thanks!
Answer by Hellium · Aug 06, 2018 at 04:15 PM
public class SaveManager : MonoBehaviour
{
private ISavable[] savables;
public void Save()
{
if( savables == null ) savables = FindObjectsOfType<ISavable>();
for( int index = 0 ; index < savables.Length ; ++index )
savables[index].OnSave();
}
}
That's what I ended up doing!
There's one downside though...
FindObjectsOfType only finds active objects...
I don't remember where I saw it now, but the solution I found was to load all root objects using
UnityEngine.Scene$$anonymous$$anagement.Scene$$anonymous$$anager.GetActiveScene().GetRootGameObjects()
into an array and then getting all children ISavable from each element using
GetComponentsInChildren<ISavable>(bool includeInactive)
passing true for includeInactive.
This way I had access to ISavable from every single object in the scene, active or not.
Your answer
Follow this Question
Related Questions
Can I use EventSystems to receive PointerEvents anywhere on screen? 0 Answers
How to drag gameobjects (other than ui elements) using the event trigger? 2 Answers
Can't fire a Custom Event on UI Button Touch OnClick 1 Answer
uUI - OnSelect: From Mouse/Pointer or Keyboard/Controller? 0 Answers
Adding custom BaseEventData to UnityEngine.EventSystems NOT Unity.Events 1 Answer