Ok, so I am trying to make a 2d rpg kinda akin to final fantasy with a better battle system. However, I am having trouble trying to figure out how to get my character classes between scenes. So I tried to make a static class with public variables to find out I cant do that. So here is what I need.
- I need a class to hold variables that all relate to one character
- I need to be able to change them from other scripts
- I need to be able to access them across different scenes
What would be the best way to go about doing this?
Your class should be a script you put on your player gameobject. In the Start method or Awake method of this script, you must call DontDestroyOnLoad which is exactly meant to preserve a gameobject including all its components through scene changes, thus accomplishing this.
Making everything static is an oft-chosen yet poor design choice for inter-scene persistence. Those variables that constitute defining characteristics about your player character should instead be made public properties, which are implemented like so, in C#:
public int MyProperty { get; set; }
With an int for this example, though the type could be anything. The “get” and “set” parts afterwards ensure external code can read and set this variable. Properties like the int in this example are the standard way to accomplish these things in C#, but beware that they are not serialized in Unity, so they will not appear in the editor. It’s possible to get them to do so, but if that is a requirement, the code must be slightly more involved, as you will have to declare the underlying variable exposed through the property yourself and make sure it is serialized. Such an implementation would look like this:
public int MyProperty { get { return _myPropertysInt; } set { _myPropertysInt = value; } }
[SerializeField]
private int _myPropertysInt;