I am having a similar issue.
I am creating a Weapon/Skill system that will gather all the data it needs from a ScriptableObject. In order to reduce clutter, instead of all the data being in one class, it will be put into what ever class requires the data.
So for example, if I have multiple ammo types such as Clips or Charge, in the scriptableobject I will have an enum to choose which ammo type I want to use, which would then display the appropriate serializable ammo class for me to put data into.
Example code
Click for code
using UnityEngine;
namespace SkillSystem
{
[System.Serializable]
public class Skill : ScriptableObject
{
//Other fields...
public enum AmmoType {None, Clips, Charge}
public AmmoType ammoType;
public AmmoClips ammoClips;
public AmmoCharge ammoCharge;
}
}
using UnityEngine;
namespace SkillSystem
{
[System.Serializable]
public class AmmoClips : Ammo
{
[SerializeField] int maxAmmoInClip;
[SerializeField] int maxClips;
//Ammo Code stuff...
}
}
using UnityEngine;
namespace SkillSystem
{
[System.Serializable]
public class AmmoCharge : Ammo
{
[SerializeField] int maxCharge;
[SerializeField] float chargeSpeed;
//Ammo Code stuff...
}
}
And so the editor code is something like this…
Click for Editor Code
using UnityEngine;
using UnityEditor;
using SkillSystem;
[CustomEditor(typeof(Skill))]
public class SkillEditor : Editor
{
public override void OnInspectorGUI()
{
Skill skill = (Skill)target;
skill.ammoType = (Skill.AmmoType) EditorGUILayout.EnumPopup("Ammo Type", skill.ammoType);
if(skill.ammoType == Skill.AmmoType.Clips)
{
SetProperty("ammoClips");
skill.ammoCharge = null;
}
else if(skill.ammoType == Skill.AmmoType.Charge)
{
SetProperty("ammoCharge");
skill.ammoClips = null;
}
}
void SetProperty(string fieldName)
{
SerializedProperty property = serializedObject.FindProperty(fieldName);
serializedObject.Update();
EditorGUILayout.PropertyField(property, true);
serializedObject.ApplyModifiedProperties();
}
}
So I choose which ammo type I want, it displays the correct class and all is well, except for the “… = null” part.
If I set one ammo type, choose another, and then switch back to the old one, the values were erased as expected. However, if I press play and try to access both ammo classes, none of them would return null. The ammo class I didnt have selected would just return values of 0.
The idea behind setting the classes I am not using to null would be to keep memory usage low.
In this particular case it might not be so much of an issue, but maybe down the road it would be.
Does anyone know of a way to choose which ScriptableObjects gets saved and which stay null?