How to activate command on all scripts
So basically, I am making a save system for my game. A need to save info in different scripts. Every script has a “public void Save()” which I need to activate when I want to save. So is there a way to set up a “trigger” that everyscript would be monitoring and run “save()” when that trigger is on?
One way i thought would be to create a bool on an empty gameobject, and make every script run “save()” when that bool is true. However, that seems not professional. Do you have any suggestions?
Answer by Nicole_W · May 03, 2018 at 05:05 AM
I'm not sure what sort of solution you're looking for, but you could do something like:
Make a baseclass like SaveableBehaviour that inherits from MonoBehaviour, then have all of your classes you want to have Save() called inherit from that. Then in your Start() function you can add them to a static list that's looped over in your Save() function.
For example:
public class SaveableBehaviour : MonoBehaviour {
private static List<SaveableBehaviour> saveables = new List<SaveableBehaviour>();
void Start() {
saveables.Add(this);
}
void SaveAll() {
foreach (SaveableBehaviour saveable in saveables) {
saveable.Save();
}
}
public void OnDestroy() {
saveables.Remove(this);
}
}
Then have your class inherit from it:
public class MyScript : SaveableBehaviour {
// Your stuff here
}
Please note, this is untested and just typed up on here, sorry if there are any dumb mistakes!
Your answer
Follow this Question
Related Questions
OnTriggerEnter Problems 1 Answer
Cannot Save due to file access denied WINDOWS 8 COMPUTER 0 Answers
Cannot Download files to Android device (v5.3.5f1) 1 Answer
How do i add coins in my Save Total Coin, everytime i collect more coins in the game? 0 Answers
Store Reference to a Serializable Class 0 Answers