Reference to scene objects from scriptable objects


Has anyone had similar issue and found solution for it? Any solution that i found so far is incomplete. I know there is IExposedPropertyTable interface and ExposedReference struct but I’m lacking some examples or guides how to implement it.

This may not be the best practice, but if it were up to me I’d just attach a script to the desired objects that tells them to add themselves to a list within the ScriptableObject (in Start and/or OnEnable). You’ll probably also want to make the same objects remove themselves from the list in OnDisable.

Here’s a simple example of one such script:

using UnityEngine;

public class AddToScriptableObjectList : MonoBehaviour
    // Reference to the ScriptableObject
    [SerializeField] SceneReferenceSO sceneReferenceSO;

    void Start() => AddSelfToList();
    void OnEnable() => AddSelfToList();
    void AddSelfToList() => sceneReferenceSO.objectList.Add(this.gameObject);
    void OnDisable() => sceneReferenceSO.objectList.Remove(this.gameObject);

You could then give the ScriptableObject some basic logic that empties out the list each time a new scene is loaded so that you don’t end up with any broken/invalid references belonging to previous scenes, like so:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

[CreateAssetMenu(menuName="Scene Object References")]
public class SceneReferenceSO : ScriptableObject
    public List<GameObject> objectList;
    void OnEnable() => SceneManager.sceneLoaded += OnSceneLoaded;
    void OnDisable() => SceneManager.sceneLoaded -= OnSceneLoaded;
    void OnSceneLoaded(Scene scene, LoadSceneMode mode) => objectList.Clear();