get component of gameobject that is type of base class

hello,
I have 5 scripts basically

1)Tower

2)Tower_Damage : Tower

3)TurrentLevelOne: Tower_Damage

4)Tower_Buffer:Tower

5)AttackSpeedBuff : Tower_Buffer

and then I have a shop where I can buy these towers
TurrentLevelOnePrefab and AttackSpeedBuffPrefab

and i want to have access to the AttackSpeedBuff script or the TurrentLevelOne script
but i dont know which script is attached to the bought tower

something like GetComponent(typeof(Tower)) but this one needs to be cast to (TurrentLevelOne) for example so i can have access to its methods , any ideas?

thanks in advance

There’s a bunch of ways to do this (assuming Tower is a MonoBehaviour) . Here’s a few:


Here’s a bad way to do it (to show you you can use GetComponent on subclasses):

AttackSpeedBuff speedBuffComponent = towerPrefab.GetComponent<AttackSpeedBuff>();

if (speedBuffComponent != null)
{
	// do stuff
}

TurretLevelOne turretComponent = towerPrefab.GetComponent<AttackSpeedBuff>();

if (turretComponent != null)
{
	// do stuff
}

Here’s another bad way to do it (to show you how to use typeof and GetType to determine what type a component is):

    Tower towerComponent = towerPrefab.GetComponent<Tower>();
    
    if (towerComponent != null)
    {
    	// this is true if the tower component on the prefab is an
    	// AttackSpeedBuff component or a subclass of AttackSpeedBuff
    	if (typeof(AttackSpeedBuff).IsAssignableFrom(towerComponent.GetType()))
    	{
		AttackSpeedBuff asbuff = (AttackSpeedBuff)towerComponent;
    		// do stuff
    	}
    	else if (typeof(TurretLevelOne).IsAssignableFrom(towerComponent.GetType()))
    	{
		TurretLevelOne tl1 = (TurretLevel1)towerComponent;
    		// do stuff
    	}
    }

Both of these ways work. They’re not good practice, but they’ll do what you need with minimal code reworking. A better way to do it would be to rework your classes so you can get them to do what you need them to do without your shop script knowing what specific kind of tower they are.

When I’m in this situation, I always try to refactor my classes before I resort to things like the solutions I gave above. Sometimes it takes a little creative thinking, but it’s usually doable.