Search Unity

static function within gameobject

Discussion in 'Scripting' started by TJB, Jan 18, 2010.

  1. TJB

    TJB

    Joined:
    Mar 20, 2007
    Posts:
    146
    Hi,
    a number of the built in scripts like rigidbody and networkView seem to do something like this, ie:
    rigidbody.AddForce(1,1,1);

    How could you make your own script that you could attach to a gameobject and call functions from another script on that same object like this:
    myscript.myfunction();
    instead of:
    transform.GetComponent("myscript").myfunction();
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Code (csharp):
    1. var myscript = GetComponent(MyScript);
    2. myscript.MyFunction();
    --Eric
     
  3. TJB

    TJB

    Joined:
    Mar 20, 2007
    Posts:
    146
    thanks, but is there any way to do it without the line assigning the script to a variable? I'm trying to make components work like the built in ones and want to avoid any complexities that built in components don't have so they're as familiar as possible for people to work with
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    No, but you only have to do that once if you use a private variable:

    Code (csharp):
    1. private var myscript : MyScript;
    2.  
    3. function Start () {
    4.    myscript = GetComponent(MyScript);
    5. }
    It's better for speed to cache the reference like that anyway.

    --Eric