Sueko
1
Hi there!
I have a script called ThrowableObject.cs that would like to invoke different effects depending on the type of the object throwed. Do invoke these different effect I need to call Item1Effect.cs, Item2Effect.cs or Item3Effect.cs, but I don’t want to specifically adress all type of items in this ThrowableObject.cs script.
How can I link a script to another script by dragging and dropping as I add public classes in unity?
Or is it a way to call GetComponent without having any idea about the name of the object?
Ideally, I would like to have at in my ThrowableObject.cs something like:
public Script effectScript;
And then form Unity drag and drop the Script I would like to link.
I have searched around this questions, but seems nobody had this problem, or most likely, I am looking for the wrong key Tags. Thank you for your help!!
In this case, apparently the easiest solution is to use SendMessage - it calls a function by name without knowing anything about the script where the function is declared. A common use for SendMessage is to call the “Fire” function in the currently selected weapon, no matter which it is, or to apply damage to different objects or enemies by calling their “ApplyDamage” function. You could for instance create a function called “DoEffect” in all items, and call it when the item is thrown.
If ThrowableObject is attached to the item, simply use SendMessage:
SendMessage("DoEffect");
This will call DoEffect() in any script attached to the same object as ThrowableObject.
On the other hand, if ThrowableObject instantiates the object, use a reference to it in SendMessage:
GameObject obj = Instantiate(itemPrefab, pos, rot) as GameObject;
obj.SendMessage("DoEffect"); // specify the object to SendMessage to
SendMessage accepts one optional parameter, which may be of any type - including references to classes.