Scriptable Objects for UI Data Help

In my current project, I am setting up ScriptableObjects to store data (descriptions, names, and attributes of different items) and in a portion of the UI is going to be a display. When you click on the button corresponding to an item it will open an info panel with the information on the item. What would be the best way to have the data displayed on both the info panel and the display area? If possible I would love to just be able to inter the item name for each UI button and have the texture determined by the ScriptableObject.

You could define your ScriptableObject class like this:

[CreateAssetMenu]
public class UIData : ScriptableObject {
    public string description;
    public Sprite image;
}

Then create ScriptableObject assets, inspect them, and assign the fields (description, image, etc.).

Then add a new class to your UI Button, something like:

public class UIDataButton : MonoBehaviour {
    public UIData data; //<-- ASSIGN SCRIPTABLE OBJECT HERE

    public RectTransform dataPanel; //<-- ASSIGN UI ELEMENTS
    public Text dataName;
    public Text dataDescription;
    public Image dataImage;

    void OnClick() {
        dataPanel.gameObject.SetActive(true);
        dataName.text = data.name;
        dataDescription.text = data.description;
        dataImage.sprite = data.image;
    }
}

However, I’m not quite sure what you mean by info panel and display area. The code is written so that when you click on a button, it sets the values of certain UI elements. You could always add more UI elements to the script – or, even better, break out that functionality into a separate script. So the UIDataButton would only have a reference to UIData and to the separate script. When clicked, it would pass the UIData info to the separate script, which would do its work to set up the UI elements’ content.

don’t forget that scriptable objects can have functions, they just don’t have the automatic context within a scene that MonoBehaviours do so you have to provide it. If you intend to extend the UIData class it might be worth making the OnClick function in the UIDataButton class call a base class function that can be overridden.

[CreateAssetMenu]
public class UIData : ScriptableObject
{
    public string description;
    public Sprite image;
 
    public virtual void PopulateInfoPanel(RectTransform panel)
    {
        // do stuff to panel here
    }
}


public class UIDataButton : MonoBehaviour
{
    public UIData data;
    public RectTransform dataPanel;

    void OnClick()
    {
        dataPanel.gameObject.SetActive(true);
        data.PopulateInfoPanel(dataPanel);
    }
}

(obviously it might be easier if the infopanel had a script with variables to populate than working with a recttransform directly :slight_smile: )

:slight_smile:

1 Like