So I want to manipulate hero’s stat, skill at inspector window.
Hero has many skills, so I wrote like,
HeroCustomEditor.cs
using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
using System.Collections.Generic;
[CustomEditor(typeof(HeroEditor))]
public class HeroCustomEditor : Editor {
public override void OnInspectorGUI(){
var editor = target as HeroEditor;
EditorGUILayout.LabelField("[Hero1]");
editor.hero1.name = EditorGUILayout.TextField("Hero Name", editor.hero1.name);
editor.hero1.picture = (Texture2D)EditorGUILayout.ObjectField("Image", editor.hero1.picture, typeof(Texture2D));
EditorGUILayout.LabelField("[Stat]");
editor.hero1.heroStat.strength = EditorGUILayout.IntField("Strength", editor.hero1.heroStat.strength);
EditorGUILayout.LabelField("[Skills]");
editor.hero1.heroSkills[0].name = EditorGUILayout.TextField("Hero Skill 1", editor.hero1.heroSkills[0].name);
}
}
HeroEditor.cs
public class HeroEditor : MonoBehaviour {
public Hero hero1 = new Hero();
public Hero hero2 = new Hero();
// Use this for initialization
void Start () {
Skill someSkill1 = new Skill();
hero1.heroSkills.Add(someSkill1);
}
// Update is called once per frame
void Update () {
}
}
Classes.cs
using UnityEngine;using System.Collections;
using System.Collections.Generic;
public class Classes : MonoBehaviour {
// Use this for initialization
void Start () {
}
}
[System.Serializable]
public class Hero{
public string name;
public int number;
public Texture2D picture;
public Stat heroStat;
public List<Skill> heroSkills = new List<Skill>();
}
[System.Serializable]
public class Stat{
public int strength;
public int offense;
public int defense;
}
[System.Serializable]
public class Skill{
public string name;
}
But this result error of,
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
You’re getting the ArgumentOutOfRangeException because you are assuming that editor.hero1.heroSkills always has a first skill. This is not guaranteed at all. A new object would have a zero-length heroSkills array, resulting in the above error.
You should use the serialized object instead of the target object and rethink how to create your editor.
Unfortunately that tutorials works with Unity 4.2, but not with 4.3 until I find the time to update it. That’s because it depended on attributes, and Unity changed how they are applied to arrays.
That tutorial uses a custom property drawer attribute. These used to apply to entire arrays, but now they apply to the array’s elements instead. That’s why it complains about “Property is not an array nor a list”.
On the subject, do you think it’s possible to create a PropertyDrawer for List where T : SerializableObject or something along those lines? Basically a way to redraw all lists within Unity.
I’ve given it a quick try but I’m getting some issues using T. Thought I’d throw the question out there.