How do I write a function that will work with multiple components?

I’m working on a grid game. When a cursor is over an Ally, Enemy, Item, etc… it should do different things depending on the type of component. Is there a better way than writing a bunch of statements like this for each component?

if(gameobject.GetComponenet<Ally>()) {
// do something

I’ve seen something like


before, but I don’t know how that works.

You can use Interface or Abstract class depending of your needs. In your case, I would suggest you to go for an interface called ICursorHoverAction such as this :

public interface ICursorHoverAction
    void OnCursorHover();

That way, you can simply do this in your grid:

ICursorHoverAction target = gameobject.GetComponenet<ICursorHoverAction>()
if(target != null) 

Now, when a class needs to react when the mouse hover over it, it only needs to implement that interface. For more info, see Unity’s tutorial on interfaces.