Last active
July 5, 2018 21:59
-
-
Save mao-test-h/a515bd13a2e502385e521d0e49ba1f62 to your computer and use it in GitHub Desktop.
【Unity】Inspectorに表示されている配列の要素をソートするサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspectorに表示されている配列の要素をソートするサンプル | |
namespace MainContents.Test | |
{ | |
using UnityEngine; | |
using System.Collections; | |
[CreateAssetMenu(menuName = "ScriptableObjects/InspectorArraySortTest", fileName = "InspectorArraySortTest")] | |
public class InspectorArraySortTest : ScriptableObject | |
{ | |
// ソート対象 | |
public GameObject[] sortObjects1; | |
[SerializeField] GameObject[] sortObjects2; | |
// 配列以外無視 | |
public GameObject ignore1; | |
[SerializeField] GameObject ignore2; | |
[SerializeField] int ignore3; | |
[SerializeField] string ignore4; | |
} | |
} | |
#if UNITY_EDITOR | |
namespace MainContentsEditor.Test | |
{ | |
using UnityEngine; | |
using UnityEditor; | |
using System.Linq; | |
using System.Reflection; | |
using MainContents.Test; | |
[CustomEditor(typeof(InspectorArraySortTest))] | |
public class InspectorArraySortTestEditor : Editor | |
{ | |
// Inspector表示用 | |
public override void OnInspectorGUI() | |
{ | |
base.OnInspectorGUI(); | |
var target = (InspectorArraySortTest)this.target; | |
var fields = typeof(InspectorArraySortTest).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); | |
foreach (var field in fields) | |
{ | |
// フィールド名のみ取得 | |
var name = field.ToString(); | |
name = name.Substring(name.IndexOf(" ") + 1); | |
// UpperCamel変換 | |
string upper = name[0].ToString().ToUpper(); | |
name = upper + name.Remove(0, 1); | |
// GameObjectの配列以外無視 | |
GameObject[] objs = field.GetValue(target) as GameObject[]; | |
if (objs == null) { continue; } | |
EditorGUILayout.BeginHorizontal(); | |
// 昇順ソート | |
if (GUILayout.Button(name + " : Sort(昇順)")) | |
{ | |
// 名前でソート | |
objs = objs.OrderBy(_ => _.name).ToArray(); | |
field.SetValue(target, objs); | |
this.SaveAssets(); | |
} | |
// 降順ソート | |
if (GUILayout.Button(name + " : Sort(降順)")) | |
{ | |
objs = objs.OrderByDescending(_ => _.name).ToArray(); | |
field.SetValue(target, objs); | |
this.SaveAssets(); | |
} | |
EditorGUILayout.EndHorizontal(); | |
} | |
} | |
void SaveAssets() | |
{ | |
// ダーティーフラグを立ててそのままSave Projectを掛ける | |
EditorUtility.SetDirty(target); | |
AssetDatabase.SaveAssets(); | |
} | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment