Property Drawer Doesn't Show Property
Hello everyone. I'm trying to create a property drawer to show stats for my game so I can edit them outside of code. Each stat is an instance of the BaseStat class. I already have a custom editor working to show the list of stats, but each element does not show the properties it is supposed to. Sometimes it just doesn't show, but other times it gives me a null reference exception. Here is the BaseStat class: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BaseStat {
public List<StatBonus> BaseAdditives { get; set; }
public int BaseValue { get; set; }
public string StatName { get; set; }
public string StatDescription { get; set; }
public int FinalValue { get; set; }
public BaseStat (int baseValue, string statName, string statDescription) {
this.BaseAdditives = new List<StatBonus>();
this.BaseValue = baseValue;
this.StatName = statName;
this.StatDescription = statDescription;
}
public void AddStatBonus(StatBonus statBonus) {
this.BaseAdditives.Add(statBonus);
}
public void RemoveStatBonus(StatBonus statBonus) {
this.BaseAdditives.Remove(this.BaseAdditives.Find(x => x.BonusValue == statBonus.BonusValue));
}
public int GetCalculatedStatValue() {
this.FinalValue = this.BaseValue;
this.BaseAdditives.ForEach(x => this.FinalValue += x.BonusValue);
return FinalValue;
}
}
I'm not sure if it doesn't work because it is a C# property and not a variable, but here is the property drawer script that I currently have set up to display the StatName property only:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(BaseStat))]
public class BaseStatDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
Rect contentPosition = EditorGUI.PrefixLabel(position, label);
EditorGUI.PropertyField(contentPosition, property.FindPropertyRelative("StatName"), GUIContent.none);
}
}
Any other code improvement suggestions would also be helpful. Thanks in advance!
Answer by Adam-Mechtley · Jan 13, 2017 at 10:56 AM
Hi! Is your BaseStat
class marked with System.Serializable
?
Sorry for the late reply. I haven't worked on this project since I asked the question. BaseStat
was not marked as System.Serializable
, and marking it as System.Serializable
had no effect. I still get a NullReferenceException on this line: EditorGUI.PropertyField(contentPosition, property.FindPropertyRelative("StatName"), GUIContent.none);
I still think it might have something to do with StatName
being a property and not a variable, but I have yet to find a solution for this.
Can you edit your original post to include the actual stack trace?