#making instances of ScriptableObjects?

1 messages · Page 1 of 1 (latest)

crisp lake
#

i have a weapon system based on SO that has a base weapon class and some inheritance that are different types of weapon and each of them has the CreatAssetMenu. and i also have a player with a ChangeWeapon function that looks like this:

 public void WeaponChange(Weapon weapon)
    {
        CurrentWeapon = weapon;
        CurrentWeapon.StartServerRcp();
        WeaponMeshFileter.mesh = weapon.displayMesh;
        WeaponMeshRenderer.material = weapon.material;
    }

now i want to an instance of the weapon SO Object not the Object itself (so when i run the functions inside the SO it dosn't change the actual values)

sand spindle
#

I recommend making this a generic method (so that means not using the overload that accepts string or Type)

crisp lake
sand spindle
#

Use the generic overload

crisp lake
sand spindle
#

The Unity docs don't make it clear (the Unity docs are awful) - but there is a generic overload to CreateInstance

#

So you can do ScriptableObject.CreateInstance<SomeWeaponClass>()

#

But you want it to use whatever type the caller of the WeaponChange method passes. So you can make your WeaponChange also generic, by doing something like:

public void WeaponChange<TWeapon>(TWeapon weapon) where TWeapon : Weapon
{
    // code
}
#

This will let the method accept anything that inherits Weapon, which you can then pass to ScriptableObject.CreateInstance - you also have access to the properties inside weapon because of the constraint where TWeapon : Weapon

#

You've likely already used generics. GetComponent is generic. When you do GetComponent<Rigidbody>() for example, Rigidbody is a generic argument. The method returns whatever type you request it to return

crisp lake
#

i did that but im getting this error. what am i doint wrong?

sand spindle
#

Oh, is Weapon not a ScriptableObject?

#

I was under the assumption that it is

crisp lake
sand spindle
crisp lake
#

oh i forgot to save.

#

thanks.

sand spindle
#

Ah

crisp lake
#

but i still get this error.

sand spindle
#

If you're getting that error now, you should've also been getting that error initially

sand spindle
#

From the looks of the error, it appears CurrentWeapon is of type ScriptableObject not Weapon

crisp lake
sand spindle
#

You are, but if CurrentWeapon is declared with a base type (such as ScriptableObject), it will upcast to that type. So the compiler doesn't know what StartServerRcp is, because Unity didn't make a method with that name in ScriptableObject

crisp lake
#

oh that makes sense.

#

this is what using python for too long does to your brain.

sand spindle
#

Change the type to Weapon (assuming it'll always be a Weapon or a class that inherits it)