Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    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:
    7,462
    Is the object marked as Static?
     
  3. Deleted User

    Deleted User

    Guest

    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:
    7,462
    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:
    7,462
    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