Search Unity

Reference a ScriptableObject in a static class?

Discussion in 'Scripting' started by Shack_Man, Apr 22, 2019.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    Edit: I guess I can just load it from resources...I'll still leave this thread open to see if there are other ways.

    Since the Scriptable Object is part of the assets and not an instance, shouldn't in be possible in theory to assign a reference to it in a static class? Anyway to do that in practice? I have a static class with static methods that need to know quite a few things about the current game state, and scriptable objects would be great to avoid having a lot of parameters.
     
    Last edited: Apr 22, 2019
    ghostitos and kcfos like this.
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    Yes, Resource.Load might be the thing you want.
    Also, [RuntimeInitializeOnLoadMethod] if you need to load it somewhere without attaching a MonoBehaviour.
     
    Shack_Man likes this.
  3. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    I didn't know about that attribute, that seems like exactly what I need, thanks!
     
  4. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,609
    kcfos and Shack_Man like this.
  5. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    This will not work in the build by the way.
    .OnValidate runs upon change / play / build / script reload, but the reference to the Instance is never serialized, so it will be null.

    I'd say this is a really poor design choice, but if you want to make it work in build - use Awake or OnEnable to push the static instance on top of OnValidate.
     
  6. Jon50

    Jon50

    Joined:
    Jan 28, 2018
    Posts:
    5
    You're completely right.
    The reference will always return null, I guess I didn't see that, my desperation is making me blind. *Oups*
    I might delete the post, since it is a totally invalid solution.
    Oh well ‍¯\_(ツ)_/¯