Search Unity

TMPro and Scriptable Object not working.

Discussion in 'UGUI & TextMesh Pro' started by Bufferoverflovv, Mar 19, 2020.

  1. Bufferoverflovv

    Bufferoverflovv

    Joined:
    Dec 26, 2016
    Posts:
    10
    I'm trying to implement TextMeshPro elements into a scriptable object so I can access them from other classes and not depend on a Singleton "UI Manager" however I have a strange bug.

    I've setup my scriptable object like so

    Code (CSharp):
    1. using UnityEngine;
    2. using TMPro;
    3.  
    4. [CreateAssetMenu(menuName = "Manager Data/HUD")]
    5. public class HUDData : ScriptableObject
    6. {
    7.     [Header("3,2,1 GO! Text Element")]
    8.     public TextMeshProUGUI countdownText; //The 3,2,1 GO count down
    9.     [Header("Count Down Element")]
    10.     public TextMeshProUGUI checkpointTimerText; //Time left until reach next checkpoint
    11.     [Header("Lap Timer Elements")]
    12.     public TextMeshProUGUI lapTimeText; //Text element that contains the lap time
    13.     public TextMeshProUGUI BestLapTime; //Text element that contains the best lap time
    14.     [Header("Lap Element")]
    15.     public TextMeshProUGUI Laps; //Text element that contains the number of laps completed + Max Laps
    16. }
    I've setup a blank scene with just my UI and have dragged my UI elements into the asset file.

    When I press play however it seems all the references I have made to the TMPro elements in my asset file disappear or destroy themselves on load.

    I'm not really sure what to do or perhaps I have setup my scriptable object incorrectly?

    Version of Unity I am on is 2019.3.0f6

    Any help would be appreciated.
     
    Last edited: Mar 19, 2020
  2. Exentro

    Exentro

    Joined:
    Oct 8, 2013
    Posts:
    36
    TextMeshProUGUI are components of a GameObject, so living in a scene.
    A ScriptableObject is an asset, so living in the project.
    When starting, unity starts by initializing the project and thus the assets.
    The scenes, even the main loaded first, come later.
    Thus your references can't survive since they do not exists when the asset is loaded.
    You can set a reference to a component in an asset a runtime when they are both loaded, but unloading the scene will also break those references. But you can have them at start.

    However, since the asset are loaded first, component can have a reference to them without issue.
    You can maybe create a manager gameobject that keeps a reference of the ScriptableObject instance and fill it with your component in it Start or Awake method.