- Home /
Help with Structs and Custom Inspector
Currently trying to build a custom inspector, and I've hit a bit of a wall. Haven't had much experience with Unity, so bear with me if this seems easily obvious.
I have a given struct:
public AttackProfileInfo[] attackProfiles;
[Serializable]
public struct AttackProfileInfo
{
public float animationDuration;
public HitProfile hitProfile;
public float initialDamage;
}
And I am not sure how to get the relevant information to display in a custom inspector. I tried using SerializedObject/SerializedProperty with no success.
SerializedObject profiles;
SerializedProperty animationDuration;
profiles = new SerializedObject(PlayableCharacters.AttackProfileInfo);
animationDuration = profiles.FindProperty("animationDuration");
EditorGUILayout.PropertyField(animationDuration);
new SerializedObject isn't working. "PlayableCharacters.AttackProfileInfo is a type, which is not valid in the given context".
Any guidance on where I'm going wrong here would be muchly appreciated. Thanks in advance.
Answer by DJCrashFest · Nov 21, 2018 at 06:14 PM
After some time, I have figured out the answer I was looking for. Turns out making this is an array added a bit more of the complexity.
First step, is to search out the original variable name, so in this case:
var attackProfileArray = serializedObject.FindProperty("attackProfiles");
From there, I set a simple indexer variable for looping:
int indexer = 0;
Then you can use a combination of GetArrayElementAtIndex with FindPropertyRelative, which gets the field in the struct, so:
hitProfileArray.GetArrayElementAtIndex(indexer).FindPropertyRelative("animationDuration").floatValue = EditorGUILayout.FloatField("Animation Duration", PlayableCharacters.attackProfiles[indexer].animationDuration);
hitProfileArray.GetArrayElementAtIndex(indexer).FindPropertyRelative("hitProfile").objectReferenceValue = (HitProfile)EditorGUILayout.ObjectField("HitProfile", PlayableCharacters.attackProfiles[indexer].hitProfile, typeof(HitProfile), true);
Which is all put into a loop, so it can be iterated. The loop is surrounded with BeginChangeCheck() and EndChangeCheck()).
If changes are detected with EndChangeCheck(), then serializedObject.ApplyModifiedProperties() is called.
Answer by hectorux · Nov 05, 2018 at 08:18 PM
Try to use a class instead of a struct, in Unity i have never used struct, also to make a custom inspector you need a script with the editorBehviour and set which script you want to set custom.
Thanks for the reply. Unfortunately, I cannot change how the structs have been created. This is also only a sample of the code since this is part of a larger editor script.
Usually, with this kind of things i make a for an inside it putfor every custom variable inside the structure i made Edit: Ex: for(int i=0;i