Trying to create a generic functions for instantiations

Hello,
I’ve been trying to create a custom function for instantiating modules/scriptable objects.

The idea was that I’d input the “prefab” scriptable object and the object that was supposed to hold the instance of the scriptableObject.

public static void CreateComponentInstance<T>(T _Type, T _instance) where T : Object
    {
        if (_Type == null) Debug.Log("No instance of _Type entered.");
        else _instance = Object.Instantiate(_Type);
    }

I would then execute this function like this:

Util.CreateComponentInstance(mainDriveType,mainDrive);

The problem is after executing this, “mainDrive” is still null. And I don’t really understand why. If I put an object into a function, I’m just transferring a reference, right? So if I change something with the reference, I should also change the original object? _instance isn’t null after the instantiation, but “mainDrive” is.

What did I get wrong here?

Method parameters are always passed by value (== copied) unless you have a “ref” or “out” parameter. For more information see my answer over here.

Something like this would work:

public static void CreateComponentInstance<T>(T aPrefab, ref T aInstance) where T : Object
{
    if (aPrefab == null)
        Debug.Log("No prefab provided.");
    else
        aInstance = Object.Instantiate(aPrefab);
}

I don’t quite see the point of your method though. Your method name “CreateComponentInstance” also doesn’t make much sense because that’s not what that method does- All you do is creating a new object if the provided prefab / source object is not null. The newly created object is stored in the variable that is passed in by reference. So it’s just the same as Instantiate but does log a message if no source object is provided-