1. We're looking for feedback on Unity Starter Kits! Let us know what you’d like.
    Dismiss Notice
  2. Unity 2017.2 beta is now available for download.
    Dismiss Notice
  3. Unity 2017.1 is now released.
    Dismiss Notice
  4. Introducing the Unity Essentials Packs! Find out more.
    Dismiss Notice
  5. Check out all the fixes for 5.6 on the patch releases page.
    Dismiss Notice
  6. Help us improve the editor usability and artist workflows. Join our discussion to provide your feedback.
    Dismiss Notice

How do I change an object's position?

Discussion in 'Scripting' started by ctowers, Jul 17, 2017 at 3:09 PM.

  1. ctowers

    ctowers

    Joined:
    Jun 30, 2017
    Posts:
    21
    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:
    4,489
    Is the object marked as Static?
     
  3. JayMounes

    JayMounes

    Joined:
    Oct 17, 2016
    Posts:
    96
    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:
    21
    @LaneFox no the object isn't marked as static
     
  5. LaneFox

    LaneFox

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

    ctowers

    Joined:
    Jun 30, 2017
    Posts:
    21
    @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:
    4,489
    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:
    21
    That was the issue. Thanks