Search Unity

HOw do i chnage the position of an object?

Discussion in 'Scripting' started by TRG96, Jul 23, 2011.

  1. TRG96

    TRG96

    Joined:
    Mar 26, 2011
    Posts:
    102
    I have two empty game objects attached to my character, one on the hip and one on the hand and I have a gun which is attached to the empty game object on the leg and I want to change the position of the gun and set it to the empty game object which is attached to the hand so when I press the K key the guns appears in the hand. How can i do this?

    I have tried this

    Code (csharp):
    1. var gun : Transform;
    2.  
    3. function update ()
    4. {
    5.             var gun = Instantiate (gun, transform.Find("SpawnPoint2").transform.position, Quaternion.identity);
    6. }
    This script is just instantiating the gun at spawn point 2 and the gun just stays there, I want the 1 gun which is already in the scene to change its position and show up at spawn point 2 and attach it to the hand. Thanks
     
    Last edited: Jul 23, 2011
  2. pezz

    pezz

    Joined:
    Apr 29, 2011
    Posts:
    606
    Create another empty gameobject. put it in hand.
    When you press "k" set guns position and rotation to the empty gameobject in hand.
     
  3. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    a little confused

    First, you have a gun in the scene.... however you are instantiating one?

    I assume that you want to do something like this:

    Code (csharp):
    1.  
    2. gun.transform.position=gameObject.Find("SpawnPoint2").transform.position;
    3. gun.transform.rotation=gameObject.Find("SpawnPoint2").transform.rotation;
    4. gun.transform.parent=hand.transform;
    5.  
     
  4. TRG96

    TRG96

    Joined:
    Mar 26, 2011
    Posts:
    102
    Thanks for the reply and script, its working fine =)

    However the second line of your script

    Code (csharp):
    1. gun.transform.rotation=gameObject.Find("SpawnPoint2").transform.rotation;
    was giving me errors, saying something about Quaternion so I took that line out and it works fine.

    Code (csharp):
    1. function gunsdrawn ()
    2. {
    3. if (GunsDrawn == GunsDrawn)
    4. gameObject.Find("gun1").transform.position = gameObject.Find("SpawnPoint2").transform.position;
    5. gameObject.Find("gun1").transform.parent = gameObject.Find("SpawnPoint2").transform;
    6. if (GunsDrawn == !GunsDrawn)
    7. gameObject.Find("gun1").transform.position = gameObject.Find("SpawnPoint").transform.position;
    8. gameObject.Find("gun1").transform.parent = gameObject.Find("SpawnPoint").transform;
    9.  
    10. print (GunsDrawn);
    11. }
     
    Last edited: Jul 23, 2011
  5. Pradeep-Patel

    Pradeep-Patel

    Joined:
    Mar 31, 2011
    Posts:
    96
    u can also use Vector3Lerp it will easy