【问题标题】:Unity not showing custom serialized class field in inspectorUnity 未在检查器中显示自定义序列化类字段
【发布时间】:2021-06-12 07:13:17
【问题描述】:

我有一个简单的类,上面有 [System.Serializable] 属性,但我不确定为什么该字段没有显示在检查器中。

[System.Serializable]
public class Room
{
    [SerializeField] private Room m_parent;
    [SerializeField] private Vector2Int m_location;

    public Room parent => m_parent;
    public Vector2Int location => m_location;

    public Room(Vector2Int location, Room parent)
    {
        m_location = location;
        m_parent = parent;
    }
}

*上面的代码被剥离以突出显示未显示的字段。

这是一个使用上述类的精简脚本:

public class DungeonLayoutGenerator : MonoBehaviour
{
    [SerializeField] protected List<Room> m_rooms;

    [SerializeField] protected int m_walkLength = 10;

    public byte[,] dungeonLayout { get; protected set; }

    private int m_walkCount = 0;

    private List<Vector2Int> SquareDirections = new List<Vector2Int>
    {
        new Vector2Int(1, 0),  // East
        new Vector2Int(-1, 0), // West
        new Vector2Int(0, 1),  // North
        new Vector2Int(0, -1), // South
    };

    private void Start()
    {
        m_rooms = new List<Room>();
        Generate(0, 0, null);
    }

    private void Generate(int x, int y, Room parent)
    {
        // Exit Conditions:
        if (m_walkLength > 0 && m_walkCount >= m_walkLength) { return; }
        if(CountSquareNeighbors(x, y, (byte)MapPart.Empty) >= 2) { return; }

        // Set current location:
        dungeonLayout[x, y] = (byte)MapPart.Empty; // Enum defined in another class.
        Room room = new Room(new Vector2Int(x, y), parent);
        m_rooms.Add(room);
        parent = room;
        
        // Increment Counter if we are counting walkLength:
        m_walkCount++;

        // Bail, We have generated enough rooms:
        if (m_walkCount >= 10) { return; }

        // Randomize our directions:
        SquareDirections.Shuffle(); // Defined in Extensions.cs

        // Reccursive Calls:
        Generate(x + SquareDirections[0].x, y + SquareDirections[0].y, parent);
        Generate(x + SquareDirections[1].x, y + SquareDirections[1].y, parent);
        Generate(x + SquareDirections[2].x, y + SquareDirections[2].y, parent);
        Generate(x + SquareDirections[3].x, y + SquareDirections[3].y, parent);
    }
}

当我运行游戏时,一切都按预期工作,但是当我在检查器中展开 m_rooms 字段时,我只看到 Vector2Int 并且 m_parent 字段没有显示。我在 Room 类的构造函数中添加了一些调试代码,以确保只有创建的第一个 Room 具有 m_parent 的空值。我错过了什么吗?

提前致谢。

【问题讨论】:

  • 你有一个嵌套的Room .. unity 需要序列化无限数量的房间才能在 Inspector 中呈现这种结构 => 他们没有

标签: c# unity3d serialization


【解决方案1】:

您需要编写自定义编辑器脚本,以便 unity 能够在检查器中绘制它。现在统一不知道如何在检查器窗口中显示它。你可以在 youtube 上找到一些关于如何编写编辑器脚本的教程。

【讨论】:

  • 所以 Unity 知道如何绘制房间集合,但它需要知道如何绘制对每个内部房间引用的引用?
  • 没有。 Unity 不知道如何绘制自定义类。您应该通过编辑器脚本使用 override void ongui 来指定它。
猜你喜欢
  • 1970-01-01
  • 2019-07-12
  • 2017-11-15
  • 2012-11-01
  • 2018-07-12
  • 2017-04-21
  • 1970-01-01
  • 2011-02-14
  • 2021-09-21
相关资源
最近更新 更多