HI Community, does anyone know about ‘dynamic cast’ in c#? I have no idea to do that .
Here is my code :
public class AttackBehavior : ScriptableObject {
}
public class ShootBehavior : AttackBehavior {
}
public class HackBehavior : AttackBehavior {
}
public class Player : MonoBehavior{
AttackBehavior attackor ;
void SetAttack(string attackBehaviorName ){
// the normal way
if(attackBehaviorName == "ShootBehavior" )
attackor = (ShootBehavior) ScriptableObject.CreateInstance(typeof(ShootBehavior));
else if(attackBehaviorName == "ShootBehavior" )
attackor = (HackBehavior) ScriptableObject.CreateInstance(typeof(HackBehavior));
// any way to create the instance directly ? someting like this?
// attackor = ( 'get type from attackBehaviorName' ) ScriptableObject.CreateInstance( 'get type from attackBehaviorName' );
}
}
I answered previously with how to dynamic_cast in C#, but I don’t think that’s what you want after looking at your example. It looks like you want to create an instance of an object from the type?
Type MyAttackType = typeof(ShootBehavior);
AttackBehavior attackor = ScriptableObject.CreateInstance(MyAttackType) as AttackBehavior;
dynamic casting would normally be done through reflection I guess.
But in your case you don’t really need it, from your example I do not even see why you would need 2 different scriptable objects or scriptable objects at all.
sounds like a simple bullet monobehavior with a public enum with the bullet types that you set (calculating the right enum value through the enum class and getting it straight from the string) would be more than enough.
Yes, That is what I want. And I change your code into this:
// Type MyAttackType = typeof(ShootBehavior);
Type MyAttackType = Type.GetType("ShootBehavior");
AttackBehavior attackor = ScriptableObject.CreateInstance(MyAttackType) as AttackBehavior;