Situation:
I’m making a base class from which other classes inherite function, etc. This classes have all different names(of courcse)
Problem:
Now I want to call a function(let’s say “SuperFunction()” ) and get a value from it. The script should return the first component that has a GetAmmo() function in it. Is this possible?
You can use Interfaces to ensure a common interface that all your weapons have to provide. Your class is still derived from MonoBehaviour but in addition you implement an interface. You can use GetComponent() to get a reference to your attached weapon script.
public interface IWeapon
{
int GetAmmo();
}
public class MyBaseClass : MonoBehaviour
{
}
public class Shotgun : MyBaseClass,IWeapon
{
public int GetAmmo()
{
return 5; // :D implement it as you need it
}
}
Somewhere else:
MyBaseClass[] list = GetComponents<MyBaseClass>();
foreach(MyBaseClass O in list)
{
if (O is IWeapon)
{
// Yeah, it's a weapon
IWeapon weapon = (IWeapon)O;
weapon.GetAmmo();
}
}
edit
I was wrong about GetComponent. You can use it also on interfaces, thanks Mike. So it's possible to get the attached weapon only be the common used interface:
IWeapon weapon = GetComponent(typeof(IWeapon)) as IWeapon;
if (weapon != null)
weapon.GetAmmo();
Unfortunately Unity put a constraint on the generic parameter so you can use it only for types that are derived from Component. Here's the implementation:
public T GetComponent<T>() where T : Component
{
return this.GetComponent(typeof(T)) as T;
}
Maybe they remove the constraint (where T : Component) in the future. That wouldn't hurt much but it would help to use interfaces ;)