Search Unity

Serialized Non-Monobehaviour Class, Constructors, and ScriptableObjects

Discussion in 'Scripting' started by Kaldrax, Jul 14, 2019.

  1. Kaldrax

    Kaldrax

    Joined:
    Sep 14, 2017
    Posts:
    44
    Hey guys. Here's the deal:

    I have a class GameResource, a non-monobehaviour class that I use for charge-up bars and status effect buildup etc. It contains some data to store the current value, max and min values, and some code to make it regen/drain over time.

    I have it tagged System.Serializable so that I can modify it in the Inspector.

    It also has a constructor, which is used to subscribe it's GameResourceUpdate() to a GameController's (Monobehaviour) DoAllGameResourcesUpdate() delegate, which is called during the Monobehaviour's Update(). This way my GameController simply calls DoAllGameResourcesUpdate() once every frame, and all my GameResources update themselves.

    It also references some public ScriptableObjects (assigned through the inspector). These SO's just contain global values, like EnemyStaggerDrainRate.

    I'm getting some weird results from this. Null reference exceptions, multiple calls of GameResourceUpdate() that I can't explain, and SO assignments that aren't the object I assigned.

    Can anybody explain what's going on?

    PS. Yes, I'm aware that I'm sort of reinventing the wheel here, and that I could just make GameResource a Monobehaviour, but I much prefer having all my GameResources as small, easily-accessible dropdowns that are part of a Component, instead of having tons of Components all over the place.
     
  2. brownboot67

    brownboot67

    Joined:
    Jan 5, 2013
    Posts:
    375
    What you're describing is perfectly valid, and consolidating updates is a good optimization. I use patterns like this a lot.

    But you haven't provided enough detail to help debug. But it can/should work.
     
  3. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    864
    The Unity Editor is calling your class constructor multiple times during it's serialization process. I've come to terms with this by always creating an empty constructor for simple serialisable objects.
     
    Last edited: Sep 6, 2021
    Nefisto likes this.