How to 'dynamic cast' in c#?

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'   );
	}


}

any suggestion will be appreciated.

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;

Is this what you are asking for?

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.

a “c++ style” dynamic_cast is done with the as operator, and happens at runtime, returning null if the cast cannot be done.

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;

Then I can dynamic cast with the class name.

Thank your very much , Jaimi.

you’re welcome!