I’ve made an interface called IHoldable
for GameObjects that I hope to be able to pick up during the course of my game. Here’s the definition:
public interface IHoldable {
void WasPickedUp();
void WasDropped();
void WasThrown();
}
Of course, I understand that classes that implement this interface must implement all of its methods, etc. So, I have (for example) a Bomb
class. Bomb
s can be picked up, dropped, and thrown. Here’s a sketch of the Bomb
class definition.
public class Bomb : MonoBehaviour, IHoldable {
// IHoldable implementation
public void WasPickedUp(){}
public void WasDropped(){}
public void WasThrown(){}
// other stuff
public void Explode(){}
}
This script is then attached to a bomb GameObject. All is well and good so far.
Now, when playing the game, I press the “pick up” button, which triggers a function in the Player
class that searches for nearby objects and picks up the nearest one. The function runs roughly like this:
- Perform a circle cast (because it’s a 2D game) to detect nearby colliders
- Weed out colliders whose GameObjects have no classes that implement the IHoldable interface
- Select the closest of the remaining colliders by comparing all of their distances
- Set the selected one as the
heldObject
variable of my player - Send the
WasPickedUp()
message to theheldObject
My problems occur in steps 2 and 5. I don’t know how to detect whether a generic GameObject has a class that implements the IHoldable
interface, and I don’t know how to send the WasPickedUp()
message to an IHoldable
object without knowing its class in advance or being able to check that it implements the IHoldable
interface (without, of course, using Unity’s SendMessage()
function, which is a little too “blind” for my purposes). I’m quite new to interfaces, so I’m sure I’m just missing something really obvious. Thanks in advance for any help!
P.S.: I’ve done a little tinkering in iOS / Objective-C, and it offers a method called respondsToSelector:(SEL)aSelector
that can help in the introspection process (“selector” is Objective-C’s word for “method,” I think). Does Unity / C# offer anything like that?
Extra P.S.: I also tried calling GetComponent()
on heldObject and passing in IHoldable
as the type, but Unity didn’t like that at all.