Calling script functions

Hi I want to allow players to pickup items in the game. Depending on the item there should be different logics when picking up the item.

I defined a function TryPickup():boolean in every item-script.

When picking up I did:

var p:MonoBehaviour = hit.transform.gameObject.GetComponent(MonoBehaviour);
if (p.TryPickup())

I got the error that TryPickup is no member of MonoBehaviour. Then I tried:

if (p.SendMessage(“TryPickup”))

Although this compiles fine, SendMessage does not support return values.

How can I call this method and use its return value? Does monoscript somehow support interfaces or which is the preferred way to solve this in unity?

Lets say you you have a script ‘ScriptB’ and want to call ‘FunctionB’ from that script.

var myscript : ScriptB;
var myvar;

function Update ()
{
  (...)
  myscript = 
  myvar = script.FunctionB();
  (...)
}

The variable ‘myscript’ holds a reference to ScriptB. You have to assign ScriptB to it via inspector.

Alternatively, if you have a reference to a GameObject that holds target script, you can use GetComponent:
http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Components.html

var myscript : ScriptB;
var myvar;

function Update ()
{
  (...)
  myscript = hit.transform.GetComponent(ScriptB);
  myvar = script.FunctionB();
  (...)
}

but my problem is that every item i want to pick up has another script file attached to it.
They only have the function names in common.

pickupKeycard.js:

TryPickup(){…}

pickupAmmo.js:

TryPickup(){…}

You know what I mean? Depending on which item I pick up the hitresult of the raycast gives me the specific script.

Is it possible for you to derive all the “pickupxxx” classes from a single superclass that implements the PickUp method?

Sure I could do this when using C#, but with Javascript in Unity everything derives implicit from MonoBehaviour and I don’t know how to change that.

I don´t know much about Unity JavaScript, but I suppose you can write at the beginning of a script something like this

public class MyClass extends BaseClass
{
...
}

and you BaseClasse extends from MonoBehavior