- Home /
Making a Serializable class that doesn't throw "The class named 'Legacy' is not derived from MonoBehaviour or ScriptableObject!"
I have the functionality I want. My issue is that I'm getting the warning "The class named 'Legacy' is not derived from MonoBehaviour or ScriptableObject!" I want the warning to go away. It is an accurate warning, because my class, Legacy, does not extend Monobehaviour. I did this so that I may tag it as [Serializable]. I'm trying to learn about game saves and serialization from this Unity live training video.
The difference I can see between my code the trainer is that my Legacy class is in a separate file and I instantiate an array of type Legacy from my GameManager script, which does extend Monobehaviour. In the live training, the class that is serialized is a private class and he does not get this error.
Here is my Legacy class:
[System.Serializable]
public class Legacy {
public int id;
public string name;
public int fame;
public Legacy( int id, string name, int fame) {
this.id = id;
this.name = name;
this.fame = fame;
}
public void AddToLegacyManager() {
LegacyManager.legMan.legacies[id] = this;
}
}
And here is where I hardcode a few elements (within my a class derived from Monobehaviour):
void CreateLegacies() {
//Create legacy for each player
Legacy leg1 = new Legacy( 0, "Achilles", 4);
Legacy leg2 = new Legacy( 1, "Hercules", 2);
leg1.AddToLegacyManager();
leg2.AddToLegacyManager();
}
And here is where I serialize in LegacyManager:
public void Save() {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create( Application.persistentDataPath + "/playerInfo.dat");
Legacy[] legs = new Legacy[2];
legs[0] = legacies[0];
legs[1] = legacies[1];
bf.Serialize( file, legs);
file.Close();
}
public void Load() {
BinaryFormatter bf = new BinaryFormatter();
if( File.Exists( path + "/playerInfo.dat")) {
FileStream file = File.Open( Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
Legacy[] legs = (Legacy[])bf.Deserialize( file);
file.Close();
legacies[0] = legs[0];
legacies[1] = legs[1];
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613183815im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I get functionality similar to OnValidate for a custom class? 4 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Instantiating a serializable class and variable 1 Answer
C# how to setup a Binary Serialization 4 Answers