ScriptableObject Out Of Scope / Memory Help

Hi,

I have several classes that inherit from ScriptableObject. Some of these classes have properties that are also derived from ScriptableObject.

When the OnDestroy function is called I can Destroy the properties however what if one of my properties is being referenced by multiple objects? How can I know if its safe to destroy the object?
The doumentation says the OnDisable function is called when a ScriptableObject goes out of scope however i have not seen this happen so far.
How would i know if a property was being referenced elsewhere? I could implement a reference counting system but would prefer not to.

Here is an example:

public class ClassA : ScriptableObject
{
    ~ClassA()
    {
        Debug.Log( "Deleted Class A" );
    }


    void OnDisable()
    {
        Debug.Log( "OnDisable Class A" );
    }
    
    void OnDestroy()
    {
        Debug.Log( "OnDestroy Class A" );
    }
}
public class ClassB : ScriptableObject
{
    public ClassA classA;
    
    ~ClassB()
    {        
        Debug.Log( "Deleted Class B" );
    }


    void OnDisable()
    {
        Debug.Log( "OnDisable Class B" );
    }
    
    void OnDestroy()
    {        
        Debug.Log( "OnDestroy Class B" );
    }
}

My Test class

public class MemoryTest : MonoBehaviour 
{
    public ClassB bRef1;
    public ClassB bRef2;


    IEnumerator Start()
    {
        bRef1 = ScriptableObject.CreateInstance<ClassB>();
        bRef2 = ScriptableObject.CreateInstance<ClassB>();


        bRef1.classA = ScriptableObject.CreateInstance<ClassA>();
        bRef2.classA = bRef1.classA; // Share class A;
        
        yield return new WaitForSeconds( 5 );


        DestroyImmediate( bRef1 );
        DestroyImmediate( bRef2 ); // Now classA should be destroyed but it is not. How can i know its safe to destroy??
    }
}

Thanks

Karl

So I was thinking of using a reference counting system, has anyone else tried this? Any implementation methods you could recommend?

Karl

I’m encountering a similar problem trying to hook into ScriptableObject’s OnDisable message. I cannot discern when OnDisable gets called, even though the documentation says “when [it] goes out of scope.” I understand that to mean when nothing’s referencing the ScriptableObject.

As a test I created 2 scenes. The first scene contains a MonoBehaviour with a serialized reference to a ScriptableObject asset in my project tree. The second scene is empty. When I play the first scene in the Editor and trigger a scene load into the 2nd scene, I do not get an OnDisable call to the ScriptableObject.

So I am going to try manually implementing a reference counting system to do this instead.