I am using properties to limit a HP variable so they don’t go below zero.
To use the properties in the editor I have created a custom editor for them using the EditorGUILayout functions IntField and IntSlider.
The problem is that when I start the scene the values are reset to 0. If I use DrawDefaultInspector the fields it draws work like they should and save the variables. The problem is that I won’t get the slider I want.
So I was wondering if anyone could tell me if I did any thing wrong with my code.
HealthControl.cs
using UnityEngine;
using System.Collections;
/* <summary>
* A component that contains basic health management
* </summary>
* */
public class HealthControl : MonoBehaviour {
[System.Serializable]
public class HitPoints{
// Private variables holding the actual values
[SerializeField]
private int maxHP;
[SerializeField]
private int currentHP;
// The properties of the class which helps with the editor
public int maxHitPoints{
get{return maxHP;}
set{if(value<0)value=0; maxHP = value;currentHP=currentHP;}
}
public int currentHitPoints{
get{return currentHP;}
set{currentHP=Mathf.Clamp(value,0,maxHP);}
}
public HitPoints(){
maxHitPoints = 100;
currentHitPoints = maxHitPoints;
}
}
public HitPoints health = new HitPoints();
void Awake(){
}
// Use this for initialization
void Start (){
}
/* Some methods */
}
HealthControlEditor.cs
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(HealthControl))]
public class HealthControlEditor:Editor{
HealthControl thisTarget;
public void OnEnable(){
if(thisTarget==null)
thisTarget = (HealthControl)target;
}
public override void OnInspectorGUI(){
thisTarget.health.maxHitPoints = EditorGUILayout.IntField("Max hitpoints",thisTarget.health.maxHitPoints);
thisTarget.health.currentHitPoints = EditorGUILayout.IntSlider("Current hitpoints",thisTarget.health.currentHitPoints,0,thisTarget.health.maxHitPoints);
}
}