So what I am trying to assemble is a “use” button that will call some sort of “activate” function on various objects, but that activate function will come from different types of components.
For example: I have a door, and when you hit “use” will looking at the door I want it to play its opening animation. Additionally I have an item. When you hit “use” on the item I want the character to play a “pick up” animation and I want the item to disappear.
Now I know I can write a script that does either of those, or both of those if I hard code in the multiple cases, but I don’t know how many different objects with different “activate” functions I’m going to have. Is there a way to make a generic “use” function that might call a function of the same name but from an arbitrary component?
2 solutions I’ve tried are as follows:
First I made an “activator” script which accepted a unity Component as a variable.
#pragma strict
var targetComponent : Component;
var illegality : int = 0;
function Start () {
}
function Update () {
}
function activate () {
targetComponent.activate();
}
But unity called foul because “activate()” is not a function of the default Unity Component class.
My second version was to use SendMessage
#pragma strict
var targetComponent : Component;
var illegality : int = 0;
function Start () {
}
function Update () {
}
function activate () {
targetComponent.SendMessage('activate');
}
This made unity crash so I couldn’t see if I got an error at all.
My dream code would be a way to call a function of a standard name like “activate” but from an arbitrarily named component like “door” or “item” without having to add to an ever growing logic testing if a gameObject has component “door” or else component “item” or else component etc.