What is the best way to get a script-response from a game object?

I have a game object -- say, a target in a fishing game. I also have a "capture" object, the "net." When a fish collides with the net, my net gets the `OnTriggerEnter()` callback, as expected.

What I'd like to do at this point is call a function in the fish's script. What I think would be really cool is if I could do something like this:

function OnTriggerEnter (col : Collider) {
    var fishData = fishCollider.SendMessageUpwards("GetFishData");
    // etc...

and have `SendMessageUpwards` pass the message around until finally the fish's script intercepts it and returns a value that is my fishData.

...But it looks like `SendMessageUpwards()` doesn't have any return value, so no go. As a n00b to Unity, it seems that I'm stuck doing something like this:

var fishData : FishData = fishCollider.gameObject.GetComponent("FishSCript").GetFishData();

...But that just seems clumsy and overly complicated to me.

Am I missing some obvious elegance trick? Or is this just how things are done in Unity? Or am I thinking about the whole thing all wrong, and standard/best practices is something completely different?


You can shorten this:

var fishData : FishData = fishCollider.gameObject.GetComponent("FishScript").GetFishData();

to this:

var fishData : FishData = fishCollider.GetComponent(FishScript).GetFishData();

Or further:

var fishData = fishCollider.GetComponent(FishScript).GetFishData();

which uses type inferencing to type fishData depending on what GetFishData returns. You should leave the quotes out of GetComponent unless necessary, since using strings is slower and you get run-time errors instead of compile-time errors.

And yes, this is how it's done. ;)

That's probably how I'd do it (that is, by using GetComponent()). People often advise avoiding GetComponent() and similar functions due to their cost (or at least caching the return values where possible), but in this context I doubt it would be a problem.