Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Setting an int in a new scriptableobject

Discussion in 'Scripting' started by Corva-Nocta, Jun 5, 2022.

  1. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    **SOLVED**

    Hi all. I'm working with a system where I create new items as scriptable objects. Each item will have an itemID that is unique to every item. At first this was just a simple matter of setting the itemID manually, but now that my item list is getting larger it's getting harder to remember what is the next id number that I should be using.

    So I'm trying to create a custom editor for the item scriptable objects. Unfortunately I am not very good at the custom editor, and I can't seem to find the answer on Google. Basically I just want a static int to increase by 1, and set the itemID to that static id.

    The terrible code I have now, and again I'm still trying to learn the custom editor so probably everything is wrong:
    Code (csharp):
    1. [CustomEditor(typeof(Item))]
    2. public class Item_Editor : Editor
    3. {
    4.    public SerializedProperty itemID;
    5.    private static int nextItemID = 1;
    6.  
    7.    private void OnValidate()
    8.    {
    9.       itemID = SerializedObject.FindProperty("itemID");
    10.       itemID = nextItemID;
    11.       nextItemID++;
    12.    }
    13. }
    Now this code doesn't work, but it does at least show the logic of ehat I'm trying to do. I'm pretty sure the OnValidate only works for the editor script, not for the scriptable object that is created, so I'm not even sure how to make this code run when I create the scriptable object.

    EDIT: so I found the Awake function will work when the scriptable object is created, however the code runs twice, I'm assuming once for the editor script and once for the scriptable object. How do I make it run only for the object?

    On top of that, I can't just do "itemID = nextItemID;" because nextItemID isn't a Serialized property.

    So some guidance would be greatly appreciated!
     
    Last edited: Jun 5, 2022
  2. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    So.... I didn't realize you could put code into a scriptable object lol. I definitely thought for some reason that you can't do code inside a scriptable object. Anyway I got it working just find now!