Design-Time Functionality: How to Initialize/Update Private Calculated Fields

I have a script to draw gizmos in the scene at design-time. I’m using ‘Gizmos.DrawIcon’ in the ‘OnDrawGizmos’ event.

For the image for the icon, I use a serialized Texture2D field that shows on the inspector.

‘Gizmos.DrawIcon’ requires a filename (without path) and the file must be in the ‘Assets\Gizmos’ folder. To get the filename I use:

var fullPath = AssetDatabase.GetAssetPath(image);
var fname = Path.GetFileName(fullPath);

The problem is that the only place I can see to put this code is in the ‘OnDrawGizmo’ event so this code has to called constantly. I can’t put it in something like ‘Awake’ or ‘Start’ because those don’t work outside of runtime.

How could I only have this code run once at start and then also when the image is set by the user? I thought of using a property but properties can’t be serialized.

Could you just make a lazy getter and once it’s gotten stop getting it? Something like:

Texture2D backingStore;
Texture2D MyGizmoIcon {
  get
   {
     if (!backingStore)
     {
       backingStore = .... whatever you load it with
     }
     return backingStore;
   }
}

Ok thanks!

This seems to work:

    [SerializeField] private Texture2D image;
    private Texture2D lastImage;

    private string fname = "";

    public void OnDrawGizmos()
    {
        if (image)
        {
            if (image != lastImage)
            {
                var fullPath = AssetDatabase.GetAssetPath(image);
                fname = Path.GetFileName(fullPath);
                lastImage = image;
            }

            if (fname != "")
                Gizmos.DrawIcon(drawIconPos, fname, true);
        }
    }
1 Like

If the image is moved, this method will break (probably not catastrophically, but the icon won’t render properly until the editor is reloaded). When it comes to the editor I tend to be more wary about caching things, especially things that have to do with the file system.

Yes, I see what you mean. But in this case the images must be in the gizmos folder anyway so it works out ok.

If the images could be moved to any folder, I guess I would just have to get the filename each update (probably not too bad of a hit in this case.)