如何使用自定义编辑器保存在预制模式(预制编辑视图,Unity 2018 +)中进行的预制修改?

时间:2019-05-16 12:40:18

标签: c# unity3d unity-editor

我有一个预制的,上面有一个名为RoomInfo的MonoBehaviour脚本。我正在使用自定义编辑器来覆盖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();
    }

方法ContainsRemoveAdd只是帮助功能,用于将序列化属性作为列表进行操作。

我希望能够将更改应用于预制资产,以便设计人员可以创建房间预制,而这并不是要在游戏场景中进行更改。谢谢你的帮助 ! :)

0 个答案:

没有答案