定义对象时候直接分配空间和在Awake函数中分配空间有什么区别?
如题,本人在实际操作中,发现GameManager类中直接分配空间和在Awake函数中分配空间,最后在UILayoout类中Debug的时候结果不一样,不知道是什么原因。
最后也是Awake分配结果输出正常。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
private static GameManager _instance;
public static GameManager Instance
{
get
{
if (_instance == null)
{
GameObject gm = new GameObject("GameManager");
gm.AddComponent<GameManager>();
}
return _instance;
}
}
//public PlayerSetting playerSetting = new PlayerSetting();
//这里直接分配空间
public PlayerSetting playerSetting;
void Awake()
{
_instance = this;
DontDestroyOnLoad(this);
playerSetting = new PlayerSetting();
//这里Awake函数中分配空间
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
[Serializable]
public class PlayerSetting
{
public KeyCode[] defaultButton = new KeyCode[12];
public KeyCode[] currentButton = new KeyCode[12];
public int volume;
public PlayerSetting()
{
defaultButton[0] = KeyCode.W;
defaultButton[1] = KeyCode.A;
defaultButton[2] = KeyCode.S;
defaultButton[3] = KeyCode.D;
defaultButton[4] = KeyCode.Alpha1;
defaultButton[5] = KeyCode.Alpha2;
defaultButton[6] = KeyCode.Alpha3;
defaultButton[7] = KeyCode.Alpha4;
defaultButton[8] = KeyCode.Space;
defaultButton[9] = KeyCode.E;
defaultButton[10] = KeyCode.F;
defaultButton[11] = KeyCode.Z;
for (int i = 0; i < defaultButton.Length; i++)
{
currentButton[i] = defaultButton[i];
}
volume = 50;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;
public class UILayout : MonoBehaviour
{
// Use this for initialization
private void Awake()
{
}
private void Start()
{
Debug.Log(GameManager.Instance.playerSetting.currentButton.Length);
//这里输出不一样
//直接分配时候这里输出11
//Awake分配这里是12
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论