【问题标题】:custom inspector not drawing correctly自定义检查器未正确绘制
【发布时间】:2019-07-15 15:56:32
【问题描述】:

GameContainer 脚本:

public class GameContainer : MonoBehaviour
{
    public List<Game> Games;


    public void AddGame()
    {
        Games.Add(new Game());
    }

}

游戏类:

[System.Serializable]
public class Game
{
    public List<GameType> gameTypes;

    public void addGameType()
    {
        gameTypes.Add(new GameType());
    }
}

游戏类型类

[System.Serializable]
public class GameType
{

}

和我在自定义编辑器中的 OnInspectorGUI 方法

public override void OnInspectorGUI()
{
    var targetScript = target as GameContainer;
    var centeredStyle = GUI.skin.GetStyle("Label");
    centeredStyle.alignment = TextAnchor.UpperCenter;
    centeredStyle.fontStyle = FontStyle.Bold;
    EditorGUILayout.LabelField("Games", centeredStyle);

    for(int i = 0;i<targetScript.Games.Count; i++)
    {
        Game game = targetScript.Games[i];

       //here is the LINE CAUSING A PROBLEM
        Debug.Log(game.gameTypes.Count);

        GUILayout.BeginVertical(EditorStyles.helpBox);

        EditorGUILayout.Space();

        GUILayout.BeginVertical("Game Types", "window");

        if (GUILayout.Button("+"))
        {
            game.addGameType();
        }

        GUILayout.EndVertical();
        GUILayout.EndVertical();
        EditorGUILayout.Space();
    }
    if (GUILayout.Button("+"))
    {
        targetScript.AddGame();
    }
}

问题出在这一行:

 //here is the LINE CAUSING A PROBLEM
 Debug.Log(game.gameTypes.Count);

当我点击AddGame 按钮时,对于新添加的元素,此行之后的所有绘图调用都将被忽略,并且直到下一次更改代码并在编辑器中刷新时才会显示,如果我删除此行,一切正常。 但是如果我尝试使用gameType 列表,它不会在检查器中显示正确的视图。

问题是什么?

【问题讨论】:

  • 我看不到你在哪里初始化游戏类型,据我所知它会是空的。

标签: unity3d editor


【解决方案1】:

我建议使用 EditorGUILayout 而不是旧的 GUILayout 类。 这是它的文档链接: https://docs.unity3d.com/ScriptReference/EditorGUILayout.html

尽管最近 Unity 引入了一种新方法来制作自定义编辑器,称为 UI 元素。 您可以使用类似 xml、css 的语言创建具有分层架构的自己的编辑器。 这里有一些对您有用的 YouTube 链接:

https://www.youtube.com/watch?v=sVEmJ5-dr5E

https://www.youtube.com/watch?v=MNNURw0LeoQ

https://www.youtube.com/watch?v=GSRVI1HqlF4

最后你也可以查看这个漂亮的编辑器属性:

https://github.com/dbrizov/NaughtyAttributes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多