We often use Scriptable Objects to store data about our in game items. To extend what we can see in the inspector we can create a Custom Editor for our MonoBehaviours or Scriptable Objects.
All we need to do is create an Editor folder and inside create a custom script (usually called “name of your script + Editor”). The Editor folder can be placed anywhere / you can have multiple of them in your project.
Weapon Scriptable Object + Custom Editor code
Here is the code behind my Scriptable Object
[CreateAssetMenu]
public class Weapon : ScriptableObject
{
//just the data that I need the weapon to have
public string weaponName = "Sword";
public Sprite weaponSprite;
[Range(0, 1)]
public float baseHitChance = 0.5f;
[Range(0,10)]
public int weaponDamage = 3;
}
And here is the custom editor
//we need that using statement
using UnityEditor;
using UnityEngine;
//We connect the editor with the Weapon SO class
[CustomEditor(typeof(Weapon))]
//We need to extend the Editor
public class WeaponEditor : Editor
{
//Here we grab a reference to our Weapon SO
Weapon weapon;
private void OnEnable()
{
//target is by default available for you
//because we inherite Editor
weapon = target as Weapon;
}
//Here is the meat of the script
public override void OnInspectorGUI()
{
//Draw whatever we already have in SO definition
base.OnInspectorGUI();
//Guard clause
if (weapon.weaponSprite == null)
return;
//Convert the weaponSprite (see SO script) to Texture
Texture2D texture = AssetPreview.GetAssetPreview(weapon.weaponSprite);
//We crate empty space 80x80 (you may need to tweak it to scale better your sprite
//This allows us to place the image JUST UNDER our default inspector
GUILayout.Label("", GUILayout.Height(80), GUILayout.Width(80));
//Draws the texture where we have defined our Label (empty space)
GUI.DrawTexture(GUILayoutUtility.GetLastRect(), texture);
}
}
Want to learn more about Unity ?
Check out my OOP for Unity Devs video course and others !
You can also support me through Patreon:
If you agree or disagree let me know by joining the Sunny Valley Studio discord channel :)
Thanks for reading!
Peter