3

我有一个预制件,上面有一个 MonoBehaviour 脚本RoomInfo。我正在使用自定义编辑器来覆盖OnSceneGUI()以制作可点击的立方体来更改房间的出口列表。当我打开预制件进行编辑时,需要将修改应用于预制件资产,但我似乎找不到如何去做。

打开预制件时,这是预制件模式(自 Unity 2018 起)。我试过使用PrefabUtility类中的方法,但GameObject返回的((RoomInfo)target).gameObject不属于任何类型的预制件(?!?)见函数IsPartOfAnyPrefab(Object componentOrGameObject)。此外,问题只是保存预制资产,因为在 GameScene 中编辑预制实例时它可以工作。

要检查的类:

public class RoomInfo : MonoBehaviour
{
    [SerializeField, Range(1, 10)]
    private int XTile = 1;

    [SerializeField, Range(1, 7)]
    private int YTile = 1;

    [SerializeField, HideInInspector]
    private List<Vector2Int> Exits_Up = new List<Vector2Int>();

    [SerializeField, HideInInspector]
    private List<Vector2Int> Exits_Down = new List<Vector2Int>();

    [SerializeField, HideInInspector]
    private List<Vector2Int> Exits_Right = new List<Vector2Int>();

    [SerializeField, HideInInspector]
    private List<Vector2Int> Exits_Left = new List<Vector2Int>();
}

编辑:

[CustomEditor(typeof(RoomInfo), true)]
public class RoomInspector : Editor
{
    private RoomInfo room = null;

    private SerializedProperty upExitsProperty;
    private SerializedProperty downExitsProperty;
    private SerializedProperty rightExitsProperty;
    private SerializedProperty leftExitsProperty;

    private void Awake()
    {
        room = target as RoomInfo;

        upExitsProperty = serializedObject.FindProperty("Exits_Up");
        downExitsProperty = serializedObject.FindProperty("Exits_Down");
        rightExitsProperty = serializedObject.FindProperty("Exits_Right");
        leftExitsProperty = serializedObject.FindProperty("Exits_Left");
    }

    public void OnSceneGUI()
    {
        serializedObject.Update();

        for (int i = 0; i < room.XTileNb; i++) // Down
        {
            Vector3 pos = new Vector3(i + 0.5f, -0.5f, -0.5f);
            Vector2Int coordinates = new Vector2Int(i, 0);

            int index = -1;
            bool contain = Contains(downExitsProperty, coordinates, ref index);

            if (contain)
                Handles.color = new Color(0.0f, 1.0f, 0.0f, 0.8f);
            else
                Handles.color = new Color(1.0f, 0.0f, 0.0f, 0.8f);

            if (Handles.Button(pos, Quaternion.identity, 1.0f, 1.0f, Handles.CubeHandleCap))
            {
                if (contain)
                    Remove(downExitsProperty, index);
                else
                    Add(downExitsProperty, coordinates);

                Repaint();
            }
        }

        // ...
        // Repeated 3 times for up, left and right of the room

        serializedObject.ApplyModifiedPropertiesWithoutUndo();
    }

方法Contains和只是将序列化属性作为列表操作的帮助函数RemoveAdd

我希望能够将更改应用到预制资产,以便设计师可以创建房间预制,它不打算在游戏场景中更改。谢谢你的帮助 !:)

4

0 回答 0