Unity中getComponent获取数组问题

在跟着学卡牌游戏制作的过程中,遇到制作的卡牌无法显示的情况。看了一会发现获取玩家拥有的卡牌数组出现问题,在DeckManager里用getComponent获取PlayerData中的playCards失败,只获得到一个徒有其名的空数组,所以在显示的过程中找不到卡牌。

//DeckManager部分
    void Start()
    {
        PlayerData = DataManager.GetComponent<PlayerData>();
        CardStore = DataManager.GetComponent<CardStore>();

        for (int i = 0; i<PlayerData.abc.Length; i++)
        {
            Debug.Log(PlayerData.abc[i]);
        }
        Debug.Log(PlayerData.playerCards.Length);
        UpdateLibrary();
    }

    public void UpdateLibrary()
    {
        for (int i = 0; i < PlayerData.playerCards.Length; i++)
        {
            if (PlayerData.playerCards[i] > 0)
            {
                Debug.Log("开始加载");
                GameObject newCard = Instantiate(cardPrefab, libraryPanel);
                Debug.Log("复制卡牌");
                newCard.GetComponent<CardCounter>().counter.text = PlayerData.playerCards[i].ToString();
                Debug.Log("载入张数");
                newCard.GetComponent<CardDisplay>().card = CardStore.cardList[i];
                Debug.Log("载入卡牌信息");
            }
        }
    }
//PlayerData部分
    public CardStore CardStore;
    public int playerCoins;
    public int[] playerCards;
    public int[] abc = { 1, 2, 3, 4, 5, 6, };
    public TextAsset playerData;
    // Start is called before the first frame update
    void Start()
    {
        CardStore.LoadCardData();
        LoadPlayerData();
        for (int i = 0; i < playerCards.Length; i++)
        {
            Debug.Log(playerCards[i]);
        }
    }

PlayerData里打印的playerCards数组内容,确保有东西。

img

DeckManager里打印了PlayerData里自己设置的一个数组abc,确定abc里的数据都传过来了,但打印playerCards的长度显示为0。

img

求解,为什么数组abc能有数据,而playerCards里却没有数据,以及如何解决这个问题。

你的playerCards数组是在哪里赋值的?你的abc数组是有初始值的,所以无论你的DeckManager什么时候取值,他都会有值。

而playerCards在现有代码中没有赋值的地方,建议检查一下是否是代码执行顺序和预想的不一致,因为你的DeckManager是在Start中进行取值的执行的比较早,若playerCards赋值晚则会出现这种情况。