Hello everyone,
I am new to unity scripting and found a common practice to set up a singleton GameManager for persistent data across scenes. Here is the implementation:
public class GameManagerController : MonoBehaviour
{
public static GameManagerController Instance
{
get { return _instance; }
private set {_instance = value;}
}
private static GameManagerController _instance;
public float screenRatio = 1f;
public Teams sceneTeams;
void Awake(){
sceneTeams = new Teams();
if(!_instance){
_instance = this;
DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject);
}
}
}
[System.Serializable]
public class Teams
{
[NonReorderable] public List<Unit> team1;
[NonReorderable] public List<Unit> team2;
public void updateTeams(Teams newData){
team1 = newData.team1;
team2 = newData.team2;
}
}
[System.Serializable]
public class Unit{
public string name;
public int hp;
public int maxHp;
public Unit(string _name, int _hp, int _maxHp)
{
name = _name;
hp = _hp;
maxHp = _maxHp;
}
}
This GameManager is set up in the Login Scene, then Teams are updated in the next Lobby Scene. Lobby Scene has its own separate controller which makes a reference first:
public Teams sceneTeams = GameManagerController.Instance.sceneTeams;
and then updates the teams on network event:
sceneTeams.updateTeams(JsonUtility.FromJson<Teams>(e.data.GetField("teams").ToString()));
The updates are visible in the inspector, but as soon as the next Encounter Scene is loaded, the sceneTeams loses all data. Same referencing is used in the Encounter Scene to get stored data from previous scenes:
public Teams sceneTeams = GameManagerController.Instance.sceneTeams;
I have used screenRatio variable to test if other data and objects are persistent and they proved to work fine. Setting screenRatio in Lobby to 2f is reported to stay 2f when GameManagerController.Instance.screenRatio is called in the next scene. So I am wondering whether custom classes have different behavior with DontDestroyOnLoad? Or am I missing something?
DontDestroyOnLoad(sceneTeams) throws an error:
error CS1503: Argument 1: cannot convert from ‘Teams’ to ‘UnityEngine.Object’ but I have no clue how to resolve it.
Any help appreciated.