3, , . / GameObjects static.
1. static.
, , MonoBehaviour GameObject, static.
, int, bool, string, float, double. static.
, :
static int counter = 0;
static bool enableAudio = 0;
static float timer = 100;
.
, :
public class MyTestScriptNoMonoBehaviour
{
}
static MyTestScriptNoMonoBehaviour testScriptNoMono;
void Start()
{
testScriptNoMono = new MyTestScriptNoMonoBehaviour();
}
, MonoBehaviour. .
, :
, Object, Component GameObject .
1A. , MonoBehaviour
public class MyTestScript : MonoBehaviour
{
}
static MyTestScript testScript;
void Start()
{
testScript = gameObject.AddComponent<MyTestScript>();
}
, MonoBehaviour.
1B. GameObject:
static GameObject obj;
void Start()
{
obj = new GameObject("My Object");
}
, GameObject GameObject Object.
Unity Object, static.
. # 2 .
2. DontDestroyOnLoad .
, Object, Component GameObject. , 1A 1B.
, GameObject :
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
static 1A 1B:
public class MyTestScript : MonoBehaviour
{
}
static MyTestScript testScript;
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
void Start()
{
testScript = gameObject.AddComponent<MyTestScript>();
}
testScript .
3. , .
, , , . - , , , , ..
Thare - :
3A. PlayerPrefs API.
, . , :
int playerScore = 80;
playerScore:
OnDisable
void OnDisable()
{
PlayerPrefs.SetInt("score", playerScore);
}
OnEnable
void OnEnable()
{
playerScore = PlayerPrefs.GetInt("score");
}
3B. json, xml binaray, API #, File.WriteAllBytes File.ReadAllBytes .
, .
, , MonoBehaviour. , , -.
:
[Serializable]
public class PlayerInfo
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int life = 0;
public float highScore = 0;
}
DataSaver, File.WriteAllBytes File.ReadAllBytes, .
:
PlayerInfo saveData = new PlayerInfo();
saveData.life = 99;
saveData.highScore = 40;
PlayerInfo "":
DataSaver.saveData(saveData, "players");
"":
PlayerInfo loadedData = DataSaver.loadData<PlayerInfo>("players");