How to change position of an object every couple of seconds?

Hello I really could use some help with this!

How do I get a object to move randomly within a set area over a couple seconds, so the object will Spawn and then a couple of seconds later it will change position randomly.

Is there any way to achieve this? (Also I am doing this in unity 2D)


You can use InvokeRepeating() for that ! Unity - Scripting API: MonoBehaviour.InvokeRepeating

Script is to be placed of the object that moves :slight_smile:

Vector3 spawnPosition

void Start () {
   spawnPosition = new Vector3(0,0,0); //if you want to always spwan in the middle
   // use random.range if you want to spawn on a random spot (see below)
   InvokeRepeating("ChangePosition", 0, 2); //calls ChangePosition() every 2 secs

void ChangePosition () {
   transform.position = spawnPosition;
   //Compute position for next time
   spwanPosition = new Vector3 (Random.Range(-5,5), Random.Range(-5,5), Random.Range(-5,5));

Hy i use this code to make one light flash at random time,but you can rewrite this code.

public float MinX = 0; //
public float MaxX = 10;// You need this only if you want to change the position
public float MinY = 0;//
public float MaxY = 10;//

    public float minTime = 0.05f;
public float maxTime = 1.2f;

private float timer;
private Light l;       // here you can put public GameObject objectToMove;
// Use this for initialization
void Start () {
	l = GetComponent<Light> (); // here objectToMove = FindObjectOfType<GameObject> ();
	timer = Random.Range (minTime, maxTime);

// Update is called once per frame
void Update () {
	timer -= Time.deltaTime;
	if (timer <= 0) {
		l.enabled = !l.enabled;  // here if you want to change location then you can use MoveObject(); and delete the enabled thing.
		timer = Random.Range (minTime, maxTime);

        void MoveObject(){
           float x = Random.Range(MinX,MaxX);
          float y = Random.Ramge(MinY,MaxY);
         objectToMove.transform.position = new Vector3 (x, y, 0);

I don’t try the code what moves the player I modify thecode here but i think it’s working