Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Reference Non-Self Objects in Scripts

Discussion in 'Scripting' started by marty, Jun 20, 2005.

  1. marty

    marty

    Joined:
    Apr 27, 2005
    Posts:
    1,170
    In Javascript, how do I change the transform of an object from a script attached to a different object?

    Here's an example: I have scene with two objects: a b all and a box. I want a script attached to the ball to code so that when the user clicks on the ball, the box tanslates.

    I don't need the translation code, just a line showing how to reference the box object from within the script attached to the ball object.

    Thanks!
     
  2. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    The easiest way is to just create a variable target which you assign in the inspector.

    Code (csharp):
    1.  
    2. var target : Transform;
    3. function Update ()
    4. {
    5.   target.position.x += 1;
    6. }
    7.  
    target appears in the inspector and you can assign it to any transform.
    Note that this script will give you an exception if you don't assign a target.

    Another way is using tags:
    Code (csharp):
    1.  
    2. function Update ()
    3. {
    4.   target = GameObject.FindGameObjectWithTag ("Box").transform;
    5.   target.position.x += 1;
    6. }
    7.  
    Then have to create a tag "Box" and tag the box with the "Box" tag.