Search Unity

Question Scriptable enums and UnityEvents

Discussion in 'Scripting' started by PascalTheDog, Sep 6, 2021.

  1. PascalTheDog

    PascalTheDog

    Joined:
    Mar 16, 2015
    Posts:
    86
    Hey,

    I wanted to try out Scriptable enums; that is, using ScrObj's in lieu of enums. The problem with enums is that they're essentially hard-coded; they're ill-suited for situations in which the amount of potential values is likely to expand (e.g. elemental types). They're okay when the amount of potential values is essentially set (e.g. cardinal directions), but even then dealing with them usually involve convoluted code such as over-lengthy switch statements. With ScrObj's, the behavior is actually contained within those.

    So I had that idea: I'm gonna use GameState ScrObj's instead of relying on a GameState enum. My GameState class would have two methods (TransitionTo and TransitionFrom) which would be called whenever the ScrObj is set and is replaced, respectively. And those methods would call UnityEvents, so the code would be very loosely coupled; and you could basically define what to do directly in the inspector (enabling/disabling objects, displaying/hiding interfaces, swapping input maps, playing effects, etc) which is great for designers.

    Sounded great on paper. But here's the problem: ScrObj's can't take references from the hierarchy. They reside in Assets, not the Scene; so I actually can't drag'n'drop anything in those UnityEvents. And I was wondering: Is my approach fundamentally flawed, or was I onto something? Is there a way to achieve what I described with ScrObj's? I'd love to know.

    Cheers!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    HUGELY smart. Enums are serialized only as an integer, so if you rename or reorder your enums, BAM, your project silently breaks. Here are my past feverish scribblings about it:

    Enums enums are bad in Unity3D if you intend them to be serialized:

    https://forum.unity.com/threads/bes...if-not-do-something-else.972093/#post-6323361

    https://forum.unity.com/threads/unity-card-game-structure.1006826/#post-6529526

    It is much better to use ScriptableObjects for many enumerative uses. You can even define additional associated data with each one of them, and drag them into other parts of your game (scenes, prefabs, other ScriptableObjects) however you like. Teferences remain rock solid even if you rename them, reorder them, reorganize them, etc. They are always connected via the meta file GUID.

    Just make the ScriptableObjects naked, then have something else that IS in the scene, and says "I switch to this state now" for instance.