- Home /
Sendmessage - return value
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?
Answer by Bunny83 · May 21, 2011 at 09:58 PM
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 ;)
This information is supplied without liability. No syntax check ;)
I know the syntax of both languages,so you can use whatever language you want^^ I haven't known, that you can use GetComponents in that way. But does this method return also the baseclass or just the child classes?
Not entirely true. GetComponent/s(Type) works fine with interfaces (kinda), GetComponent/s() doesn't
And can I also access methods in $$anonymous$$yBaseClass when I make the list of components of this class or just the methods in its childs?
You can use any base class functions to the type you have access to. If you have a $$anonymous$$yBaseClass reference, you only get $$anonymous$$yBaseClass functions. Similarly IWeapon would give you just the IWeapon ones. If you have a Gun class which extended $$anonymous$$yBaseClass and IWeapon, and had a reference to one of those, you could use everything from all three