簡體   English   中英

Unity:無法在 Inspector 中編輯公共 Sprite[][]

[英]Unity: Can't edit public Sprite[][] in the Inspector

每次我想用這個腳本玩我的游戲時:

//...

    public Sprite[][] ObjectTypestobuy;
    public Sprite[] Characters;     
    public Sprite[] Helmets;
    public Sprite[] Weapons;
    public Sprite[] Mantles;
    public Sprite[] Shields;

void Start()
{
        ObjectTypestobuy[0] = Characters; //This is the line where the error message points to
        ObjectTypestobuy[1] = Helmets;
        ObjectTypestobuy[2] = Weapons;
        ObjectTypestobuy[3] = Mantles;
        ObjectTypestobuy[4] = Shields;
}

...它拋出以下錯誤:NullReferenceException:

> Object reference not set to an instance of an object (wrapper
> stelemref) object:stelemref (object,intptr,object) Shop_Handler.Start
> () (at Assets/Shop_Handler.cs:88)

標記為錯誤的行是這一行:

ObjectTypestobuy[0] = Characters;

我認為問題是,因為它說我應該編輯public Sprite[][] ObjectTypestobuy; 在檢查員。 但是我在檢查器中找不到它。

任何幫助都會被預先處理。

在數組中設置值之前,必須先創建數組。

void Start()
{
        ObjectTypestobuy = new Sprite[5][10]; // for example
        ObjectTypestobuy[0] = Characters; //this is the error line
        ObjectTypestobuy[1] = Helmets;
        ObjectTypestobuy[2] = Weapons;
        ObjectTypestobuy[3] = Mantles;
        ObjectTypestobuy[4] = Shields;
}

如果不創建數組,則不能在其中放置任何內容。 您會收到 null 異常,因為您試圖將某些內容放入不存在的對象中。

不幸的是,您還沒有真正初始化數組。 這種類型的數組稱為“鋸齒狀”數組。

所以,答案就在這里在這頁這里從微軟。

int[][] jaggedArray = new int[3][];

然后使用初始化器,可以填充數組:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

遺憾的是 Unity 不會序列化 Dictionary 集合。 鑒於此限制,完成我認為您要實現的目標的常見工作是執行以下操作:

using System;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public struct InventoryCollection
{
    public string Name;
    public List<Sprite> Sprites;
}

public class Inventory: MonoBehaviour
{
    public List<InventoryCollection> ObjectTypesToBuy = new List<InventoryCollection>();
}

您會注意到,現在您可以直接在 Unity 中的 Inspector 窗口中輸入項目,為了方便起見,“名稱”字段還將為 Inspector 中的項目命名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM