Search Unity

Singleton ScriptableObjects using Resources.FindObjectsOfTypeAll returns null

Discussion in 'Scripting' started by arvzg, Jul 25, 2017.

  1. arvzg

    arvzg

    Joined:
    Jun 28, 2009
    Posts:
    619
    I've got a ScriptableObject called UnlockSettings that I want to use as a Singleton. The code is like this:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Linq;
    3. public class UnlockSettings : ScriptableObject
    4. {
    5.     private static UnlockSettings _instance;
    6.     public static UnlockSettings Instance
    7.     {
    8.        get
    9.        {
    10.           if (!_instance)
    11.           {
    12.              _instance = Resources.FindObjectsOfTypeAll<UnlockSettings>().FirstOrDefault();
    13.           }
    14.          
    15.           return _instance;
    16.        }
    17.     }
    18.  
    19.   int someInt;
    20.   string someString;
    21.  
    22. }
    This ScriptableObject is designed to just contain a bunch of strings and ints that I'll need to reference in other scripts, and I've got an .asset file I've created which sits in the root of /Assets with all the data entered in.

    But I'm having some issues using it. If I close Unity completely, and open it again, hit play, any object that uses UnlockSettings.Instance won't work as FindObjectsOfTypeAll is returning null as it can't find itself.

    Oddly if I just click on the asset file once, and hit play again, now everything works.

    I think this is something to do with the way ScriptableObjects are loaded into memory? Before I click on the object it's not in memory yet, so FindObjectsOfTypeAll can't detect it.

    Am I doing something wrong, if so what is the best way of doing this?
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    That's an odd way to use a singleton. Any reason you don't assign the reference in Awake?
     
  3. arvzg

    arvzg

    Joined:
    Jun 28, 2009
    Posts:
    619
    No reason in particular, this is just the way Singleton's been written from the samples I've seen. I also prefer it this way over doing it in Awake as it only ever needs to assign the reference if it's being used. If you put it in Awake it's going to assign the reference no matter what

    The way I want to use the ScriptableObject is by calling UnlockSettings.Instance.someString. I thought by writing it as a Singleton I'd be able to access the variable without having to first Instantiate UnlockSettings and thus be able to access the string from anywhere in my code, but it isn't quite working out so well
     
    Last edited: Jul 25, 2017
    SweatyChair likes this.