- Home /
How do I get gameobjects to fire a method based on an interface?
Following the interface tutorial from here. There are a number of gameobjects in the scene that implements IDamageable
. How do I fire all void Damage(float damage)
belonging to gameobjects that implement IDamageable
?
I tried the following, but Unity says "Type has to be derived from UnityEngine.Object."
var damageableObjects = GameObject.FindObjectsOfType(typeof(IDamageable)) as IDamageable[];
foreach(IDamageable d in damageableObjects)
d.Damage(1.0f);
This is just a wild guess, because I haven't worked with Javascript. The tutorial is using C#, but in your code example above you are using javascript, so ins$$anonymous$$d use a c# script and make use of:
IDamageable[] damageableObjects = GameObject.FindObjectsOfType(typeof(IDamageable)) as IDamageable[];
foreach(IDamageable d in damageableObjects)
d.Damage(1.0f);
One can also use var in C#, the only thing wrong is the separated foreach statement.
@dmg0600 thanks for picking that up for each
, ins$$anonymous$$d of foreach.
Answer by dmg0600 · Sep 22, 2014 at 07:52 AM
Take a look at this: Link to forums
Or just make it work through inheritance instead of interfaces. It depends if you are going to use a lot of interfaces or just IDamagable, as the workaround showed in that post is not very efficiency-friendly.
Thanks for the link. Why is the proposed solution not efficient friendly? LINQ?
Not because of Linq but because it goes through all the components in the GameObject searching for all of them.
Since it is just for one GameObject there is no problem, but be careful if you want to do this for a lot of objects.
I see, menuObject.GetComponents();
goes through all the components in the gameobject. I've modified my code to use inheritance rather than using interfaces.
@dmg0600 I don't see why searching for all the components is that bad as long as you don't do it in an update callback or in a coroutine, i.e. on every frame.
It is bad if you do it often or for many objects, that is why I told if there are only a few objects it doesn't really matter.