Passing multiple Sciptable object types to another Method / Class

I have a few different scriptable object types - examples: motherboardSciptableObject, cpuScriptableObject, gpuScriptableObject, psuScriptableObject, etc. I have a script that spawns out buttons from the scriptable objects and is working. I have a listener on each button that is going to call a method in another script and pass in the ScriptableObject in the parameters (code below). This method that it calls is generic by design as it will increment components, check cost of components, etc so ScriptableObject type shouldn’t matter. I’m having issues sending the ScriptableObject in and then retrieving data from these objects. Examples below -

        public void PurchaseComponent(ScriptableObject objectToPurchase)
        {
    // This is the receiving method in the other class. Due to multiple types of scriptable objects I have to pass in the ScriptableObject type. 
        Debug.Log(objectToPurchase.objectCount);
        }

In the above code, different types of ScriptableObjects are getting passed in (motherboardSciptableObject, cpuScriptableObject, etc) but the parameter takes a ScriptableObject. How do I go about “converting” these objects back to their original scriptableobject type so I can retrieve the data within? Currently all objects in that method are of type ScriptableObject. Running objectToPurchase.GetType() returns “MoterboardScriptableObject” but I can’t do much with it. Trying to output info from the ScriptableObject results in the above code saying “Cannot resolve symbol objectCount”.

I’m fairly new with C# and Unity, but have been scratching my head the past couple days on how to solve this issue. I’ve Google’d but can’t seem to come up with the correct search terms to figure out what I’m doing wrong.

If you have generic methods on all your SO types, you should make all of them inherit from an abstract base class, or use an interface. Then, instead of your PurchaseComponent function taking in a scriptable object, it takes in the interface/base class, and you can call the generic method, which has defined behaviour for each type of SO.


E.g:

public interface IComponent
{
     public void DoWork();
}

public class CPU : ScriptableObject, IComponent
{
     public void DoWork()
     {
          Debug.Log("I am CPU");
     }
}

public class GPU : ScriptableObject, IComponent
{
     public void DoWork()
     {
          Debug.Log("I am GPU");
     }
}

And then your purchaseComponent method would be:

public void PurchaseComponent(IComponent component)
{
     component.DoWork();

     // Do other things or get values etc. 
}

You can add get;set; properties to interfaces to get data as well. @karlbonitz

@Llama_w_2Ls I think that gets me on the right track! I appreciate you taking the time to post and give some examples. Just taking a step back into C# and this helps tremendously.