In my game I’m using a powerup system, which basically works like this:
- Enemy gets killed, has random chance to drop powerup box
- Pickup powerup box to get random item
The code for giving the player a random powerup looks like this…
Type t = RandomManager.PickFromParams<Type>(typeof(PowerupInvincible), typeof(PowerupDoubleFireRate));
ply.AddPowerup<t>();
And the AddPowerup<>() method looks like this:
public void AddPowerup<T>() where T : PowerupEffect, new()
{
var powerup = new T();
powerup.Activate(this);
powerups.Add(powerup);
}
Now, the problem is the ply.AddPowerup<t>() line, because it complains that it can’t find the type t:
The type or namespace name ‘t’ could not be found (are you missing a using directive or an assembly reference?)
Does anyone know if there’s a way to fix this, or if that’s not possible, show me a better way to do it? Thanks in advance!
It sounds like you are not using generics correctly in this instance. I’m assuming
PowerupInvincible, andPowerupDoubleFireRateinherit from somePowerupBase:Then the method signature simple need to be:
Your random manager would be responsible for choosing one of the parameters, instantiating it, and then returning the instance.