Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Is it possible to create an SO from an asset via context menu?

Discussion in 'Scripting' started by microbrewer, Dec 12, 2022.

  1. microbrewer

    microbrewer

    Joined:
    Jun 6, 2020
    Posts:
    12
    Hi everyone,

    So, you know how it's possible to create a shader, then right-click the shader asset und go create > material, and the material will then automatically reference said shader? Essentially, I would like to achieve something like that for scriptable objects.

    My use case is that I have a kind of SO that is basically holds an asset property together with some data around it. So it would be really convenient if I could just right-click such an asset and go create > SO, and then the SO's asset property will be set automatically.

    Is something like that possible?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,707
    I think so... if you right click on your base SO, then select the appropriate context item (such as make new), I believe the SO you were on is still the selected object in the editor.

    I think you could use this in OnValidate() or perhaps even OnEnable()... and just do it once, eg, if the field you wish to populate is empty.

    You might need to call EditorUtility.SetDirty() after that though
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
  4. microbrewer

    microbrewer

    Joined:
    Jun 6, 2020
    Posts:
    12
    Hey, thanks for the replies, but I'm afraid neither is what I'm looking for.

    The script for my SO contains the createAssetMenu attribute. That is, the SO is created via right-click context menu. What I want to achieve is to right-click some other, already existing asset in the project folder, say a sprite asset, and then have the created SO automatically reference that sprite.

    I thought that Selection.activeObject might do the trick, but for some reasons, it's not allowed in SO constructors. :/
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,707
    Constructors aren't even allowed in SOs!

    This is Unity after all. You could never call new to make a ScriptableObject... you must always use the CreateInstance<T>() method, which then hits Awake and OnEnable.

    It's possible that by the time that happens, the Selection has changed... but that's first what I would try.

    Definitely don't try anything in the ctor. It isn't even called on the main thread!
     
  6. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,842
    Ryiah and PraetorBlue like this.
  7. microbrewer

    microbrewer

    Joined:
    Jun 6, 2020
    Posts:
    12
    Thanks, that's what I was looking for! :)