I am working in unity and I made a save system that saves to a public class PlayerStats this is not a MonoBehaviour but a class that has all the data init. My question is if there is a way if I change on var in the playerstats it change all the playerstats only having only one playerstats.
CodePudding user response:
if this class is an exposed Serializable
then not really as the Serializer will (de)serialize them all independent from another into their according serialized objects.
You might want to rather go for a ScriptableObject
.
These are mainly data container assets (similar to prefabs) you can create and then reference in multiple places so each change within such a ScriptablObject
is reflected everywhere where it is used.
E.g.
// This attribute is required so you can create instances of this ScriptableObject via
// RightClick in the Assets -> Create -> Example
[CreateAssetMenu]
public class Example : ScriptableObject
{
// your public fields here like e.g.
public int someInt;
}
As an extra: ScriptableObject
is a c#
class -> They follow all the usual rules and can implement certain methods, interfaces, can be inherited etc.
CodePudding user response:
You might want to consider some kind of state management for your PlayerStats object. I can't quite understand your question completely , but from what I can get, it is that you would like to change PlayerStats object , based on a change in the PlayerStats.someVar . One way you can do this is using events :
[System.Serializable]
public class PlayerStats
{
public StatsVariable<int> health { get; set; }
public StatsVariable<string> name { get; set; }
public PlayerStats()
{
health.OnChangeEvent = onHealthChange;
name.OnChangeEvent = onNameChange;
}
void onHealthChange(int newValue) { }
void onNameChange(string newName) { }
public void OnDestroy()
{
health.OnChangeEvent -= onHealthChange;
name.OnChangeEvent -= onNameChange;
}
}
[System.Serializable]
public class StatsVariable<T>
{
private T m_value;
public T value { get => m_value; set => setValue(value); }
public delegate void OnVarChanged<T>(T newValue);
public event OnVarChanged<T> OnChangeEvent;
void setValue(T value )
{
m_value = value;
OnChangeEvent?.Invoke(m_value);
}
}