Search Unity

2019.1 EditorTool API - how to apply default references for custom icon in inspector?

Discussion in 'Immediate Mode GUI (IMGUI)' started by Xarbrough, Apr 24, 2019.

  1. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    The docs page for EditorTool shows an example with the following two lines:

    Code (CSharp):
    1. // Serialize this value to set a default value in the Inspector.
    2. [SerializeField]
    3. private Texture2D m_ToolIcon;
    This sounds to me as if we wouldn't have to dynamically load our icons any more, but could instead serialize them with the tool. However, I couldn't get this working. First, I tried to use the CreateAssetMenu attribute and instantiate the EditorTool ScriptableObject as an asset in my project and assigned the icon texture there. But I noticed that Unity doesn't load my created instance, instead it creates its own, where the reference is not set.

    So obviously we should not create an instance, so instead, I set the default reference of the icon texture on the associated tool c# script. This makes kind of sense to me, when Unity creates its own instance it can then apply the default value. However, it just doesn't show up on my button.

    What am I doing wrong? Does the icon need to be a special format other than a default texture asset?
     
    Last edited: Apr 24, 2019
    SudoCat likes this.
  2. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    I found my answer this morning: The icon content is only applied/updated after restarting Unity. So indeed, it was correct to assign the texture reference as a "default reference" on the inspector of the tool script file.

    Additionally, it is possible to assign any other object reference, e.g. a ScriptableObject instance to store configuration data.

    However, I wonder if this approach is really the best. Default references only support objects, not regular serialized fields such as floats or strings. So, to add more data I need a separate container object. Why not simply let users serialize the entire tool as a ScriptableObject asset the way I tried initially? This way it would be very simple to store configuration data. I understand there are two major drawbacks:
    1. Users must ensure a single instance in the project (and Unity would need to handle duplicate cases with some feedback)
    2. Searching the AssetDatabase might not scale well for large projects
    But, searching the assembly for attributes and creating an instance on the fly also doesn't scale well for large code bases, right? So potentially it would make sense to enforce a specialized folder such as "Editor Default Resources" which makes searching for existing tools faster while also being easy to use.