Calling a void with the same name from different scripts based on held item

Howdy, I need to refer to a script on an object I’m holding. Each held object has a Use void with its own function.
Flashlight has a flashlight script, and a Use void which toggles the light.
Gun has a gun script, and a Use void which shoots.
How do I make the ItemFunction in “heldItem.GetComponent().Use();” dynamically adjust to find the correct script for the held item?

I’ve explored the idea of interfaces, but I’m trying to call this from inside a couple of if statements, and can’t figure out a way to do this tidily as an interface would need to be placed outside the void I’m trying to call the Use function from.

@Zombait So I did some searching and I think SendMessage should be what you’re looking for. SendMessage tells whatever scripts on the object to run a certain function (if present in scripts) with an optional parameter.

        gameObject.SendMessage(string function, optional parameter);

so I think in your case it’d be


Hopefully that works

  • Original Response:
    This doesn’t exactly dynamically adjust to find the correct script but this does try to find if the script component is available. I assume that you only hold one item at a time.

          if (heldItem.TryGetComponent(out GunScript gun))
          else if (heldItem.TryGetComponent(out FlashlightScript flashlight))

This isn’t the best if you call the trygetcomponent a lot so I’d just set all the script components at the start if possible or if you already hold all the items. Hope this helps.

I was hoping that this could be applied more widely, the gun and flashlight being example items of any number of items I’d be able to flexibly add later. I’d like to be able to drop in any prefab with an “Item” tag, and whatever script is applied to that item will define its functionality.

SendMessage does work but it has a number of problems. For example, you can end up running a private Method, which bypasses OOP principles. Secondly, you are coding in the name of a class/method which can be a problem when you come to refactor your code or separate function into separate classes and functions. This creates an unnecessary dependency and an unwanted performance problem because of Reflection.

Microsoft say: “SendMessage() and BroadcastMessage() should be eliminated at all costs. These functions can be on the order of 1000x slower than direct function calls.”

What’s the alternative? Ans: Events. To keep this short, can I please refer you to an earlier answer I gave, which explains how to use them. Do come back if you have any questions…