前往
大廳
主題

Unity遊戲研究-編輯器(1) - 在陣列中新增不同Class

冰峰Will | 2022-11-07 11:37:04 | 巴幣 212 | 人氣 429

失蹤了快要一年了,
除了我去當兵完,
也開始在一間遊戲公司裡工作,
雖然我還算很菜的那種,
但還是想分享一下最近研究的東西~

最近因為同事都喜歡做編輯器,
所以也開始研究如何做更方便的編輯器,
向底下這個:
這是我現在在處理的專案,
所以無法提供完整的程式碼,
但我可以提供我參考的程式碼~
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System;

public class TestCube : MonoBehaviour
{
  [SerializeReference]
  public TestUp[] testUps;
}
[Serializable]
public class TestUp
{
  public string[] str;
}
[Serializable]
public class TestUpInt : TestUp
{
  public int[] m_int;
}
[Serializable]
public class TestUpFloat : TestUp
{
  public float[] m_float;
}
[Serializable]
public class TestUpType : TestUp
{
  public enum Type1
  {
    None,
    Good
  }
  public Type1[] m_type;
}



[CustomEditor(typeof(TestCube))]
public class TestEditor : Editor
{
  private ReorderableList list;
  private void OnEnable()
  {
    list = new ReorderableList(serializedObject,
            serializedObject.FindProperty("testUps"),
            true, true, true, true)
    {
      elementHeightCallback = ElementHeightCallback,
      drawElementCallback = DrawElementCallback,
      onAddDropdownCallback = OnAddDropdownCallback
    };
  }
  public override void OnInspectorGUI()
  {

    serializedObject.Update();
    list.DoLayoutList();
    serializedObject.ApplyModifiedProperties();
    //base.OnInspectorGUI();

  }
  public float ElementHeightCallback(int index)
  {
    SerializedProperty element = list.serializedProperty.GetArrayElementAtIndex(index);

    return EditorGUI.GetPropertyHeight(element) + EditorGUIUtility.standardVerticalSpacing;
  }
  public void DrawElementCallback(Rect rect, int index, bool isActive, bool isFocused)
  {
    var element = list.serializedProperty.GetArrayElementAtIndex(index);

    EditorGUI.indentLevel++;
    // EditorGUI.LabelField(rect, list.serializedProperty.arrayElementType);

    EditorGUI.PropertyField(rect, element, new GUIContent(element.managedReferenceFullTypename), includeChildren: true);
    EditorGUI.indentLevel--;

  }
  public void OnAddDropdownCallback(Rect buttonRect, ReorderableList l)
  {
    var menu = new GenericMenu();
    var testup = TypeCache.GetTypesDerivedFrom<TestUp>();
    var prop = serializedObject.FindProperty("testUps");
    foreach (var test in testup)
    {
      menu.AddItem(new GUIContent(test.Name), false, () =>
      {
        // prop.arraySize += 1;
        var index = prop.arraySize;
        prop.InsertArrayElementAtIndex(index);
        var elementProp = prop.GetArrayElementAtIndex(index);
        elementProp.managedReferenceValue = Activator.CreateInstance(test);
        Debug.Log(elementProp.managedReferenceFullTypename);
        serializedObject.ApplyModifiedProperties();
      });
    }

    menu.DropDown(buttonRect);
    //var guids = AssetDatabase.FindAssets();

  }
}

如果有任何問題可以來DC群詢問,
雖然這工具還是有點BUG,
日後有空會再繼續加強的~

順便宣傳DC群
這裡包含了繪畫創作、BOT娛樂、遊戲討論、影像分享、程式交流等內容。

創作回應

更多創作