Search Unity

  1. We've closed the job boards. If you're looking for work, or looking to hire check out Unity Connect. You can see more information here.
    Dismiss Notice
  2. Unity 2017.3 has arrived! Read about it here.
    Dismiss Notice
  3. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

How do I change an object's position?

Discussion in 'Scripting' started by ctowers, Jul 17, 2017.

  1. ctowers

    ctowers

    Joined:
    Jun 30, 2017
    Posts:
    22
    I am trying to change my game object's position. I am using game.transform.position = new Vector3(0,0,2).
    The position updates but my object doesn't move. How do I get it to move?
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    5,117
    Is the object marked as Static?
     
  3. JayMounes

    JayMounes

    Joined:
    Oct 17, 2016
    Posts:
    125
    Is your Transform's position 0, 0, 2 in the world eh? Remember, every object has/is a Transform component at most basic.

    Generally to move through space usefully, you need to reference where you were last frame. I want you to start thinking about every time you Update loop runs as "a frame" because that's what it is. It'll help you in the future.

    So we want something like:

    transform.position = transform.position + transform.forward * Time.deltaTime;
     
  4. ctowers

    ctowers

    Joined:
    Jun 30, 2017
    Posts:
    22
    @LaneFox no the object isn't marked as static
     
  5. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    5,117
    Then the object is moving. Make sure you're moving the correct object.
     
  6. ctowers

    ctowers

    Joined:
    Jun 30, 2017
    Posts:
    22
    @LaneFox it isn't moving. I instantiate an object with Instantiate(game, new Vector3(0,0,2), Quaterion.identity);
    It shows up in the right spot. I then use game.transform.position = new Vector3(0,0,1) and it does not move.
     
  7. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    5,117
    Because you're targeting the prefab and not the instance.

    Code (csharp):
    1.  // Attach this to anything in the scene and choose a prefab to spawn.
    2.     public GameObject MyPrefab;
    3.     private GameObject _sceneObject;
    4.  
    5.     public void Start()
    6.     {
    7.         _sceneObject = Instantiate(MyPrefab);
    8.     }
    9.  
    10.     public void Update()
    11.     {
    12.         _sceneObject.transform.position += _sceneObject.transform.position + Vector3.forward * Time.deltaTime;
    13.     }
     
    TaleOf4Gamers likes this.
  8. ctowers

    ctowers

    Joined:
    Jun 30, 2017
    Posts:
    22
    That was the issue. Thanks