2

Suppose I have this ScriptableObject to represent a list of cards:

using UnityEngine;
using System.Collections;

[CreateAssetMenu(fileName = "CardList", menuName = "Inventory/List", order = 1)]
public class CardList : ScriptableObject {
    public string[] cardName;
    public Sprite[] cardSprite;
}

Then I create the ScriptableObject and fill it with all my cards information.

Is there a way to modify this code so that any script have access to it statically? For example, is it possible to give CardList a singleton behaviour?

I don't want to create another class, it would be easy to create a ScriptableObjectManager that could reference CardList. I'd rather call something like CardList.instance.cardName[i] directly.

Daniel
  • 7,357
  • 7
  • 32
  • 84
  • 2
    Nevermind my last comment, I missed what you are getting at. [This blog post](https://baraujo.net/unity3d-making-singletons-from-scriptableobjects-automatically/) might be more helpful here. – Ruzihm Jul 10 '19 at 20:52

1 Answers1

4

Definitely, you can create it as singleton so for this. Suppose that we have Unity Project that has file hierarchy like

UnityProject
- Assets (directory)
    Scripts
        SampleScriptableObject.cs   
- Resources (directory)
    SampleScriptableObject.asset
- Project
- ..etc

in "SampleScriptableObject" class will be like

public class SampleScriptableObject<T> : ScriptableObject where T : ScriptableObject  
{
    private static T _instance;
    public T GetInstance()
    {
        if (_instance == null)
        {
            _instance = Resources.Load(typeof(T).Name) as T;
        }
        return _instance;
    }
}

you can use scriptable object as singleton as you want.

Brian Choi
  • 733
  • 5
  • 14