transform.position question

Hello,
I am trying to do something fairly simple but I feel like I may be making it more difficult than it really is. I am trying to get an object to be set at a different location every other second or so. I am trying to get a cube to spawn at a Vector3(0,0,0) and then move to Vector3(0,5,0), and then to a Vector3(5,5,0), and then to a Vector3(5,0,0) and then back to the Vector3(0,0,0). This should be an ongoing loop. I have attached what I have so far, but why do I not see anything moving when I run the game? The script is attached to an empty game object and I have the prefab set in the Inspector panel. It spawns the cube but I do not see anything moving. Any help will be appreciated, thanks!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public GameObject todo;  //create game object
  
    int x = 0; //counter


    // Start is called before the first frame update
    void Start()
    {
        Instantiate(todo);
        todo.transform.position = new Vector3(0, 0, 0);
    }

    // Update is called once per frame
    void Update()
    {
      
        if (++x % 100 == 0)
        {
         

         
            todo.transform.position = new Vector3(0, 5, 0);
            todo.transform.position = new Vector3(5, 5, 0);
            todo.transform.position = new Vector3(5,0,0);


        }
       
       
       
        }
    }

Assuming your if statement runs, it’s only going to use the last set. As it is, you’re trying to move the cube 3 times in a single frame. So in the end, it will only land at the last position you set it at. You’ll probably not catch it moving in a single frame. It will just end up at (5,0,0) every time the if statement hits.

The ++x will increment it.

1 Like

Ops, my bad :smile:

This.

Also, once you fixed that, you’ll need to save the reference to the instantiated object in a field. At the moment, you’re only addressing the prefab.

Pre- and post-increment include assignment, it’s just a useful shorthand writing for something like x +=1, or x = x+1.

Adding to what others have said, you are also moving your prefab object, not the object you create in the start method as you have no reference to it.

1 Like