# How do you randomize Vector3 offset (x, y, z) values overtime in script?

Hi there!

I am new to script writing. I currently have a script that tracks a player:

using UnityEngine;

public class camera : MonoBehaviour {

``````public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;

void LateUpdate ()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed * Time.deltaTime);
transform.position = smoothedPosition;

transform.LookAt(target);
}
``````

}

I want the Vector3 offset values (x, y, z) to change every 10 seconds so that the camera re-manuevers itself around the player. Does anyone know how to change the Vector3 offset values in script? So for instance every 10 seconds the values of (x, y, z) randomly change between values of let’s say -5 and 5? ie. (3, 2, -2) … (-2, 1, 5).

Thank you

So the solution comes in two parts, one for the timer and one for the actual RNG. I don’t think there is a Vector3.Random yet so you will have to assign each axis separately. To create a random Vector3, you can use the following code:

``````Vector3 randomVector = new Vector3(Random.Range(-5f, 5f), Random.Range(-5f, 5f), Random.Range(-5f, 5f));
``````

You can of course assign it directly to the offset, or assign the randomVector to the offset, your choice.

For the timer part, there are many ways to do this. It think the best way for a beginner would be to just have a float as a time, and use Time.deltaTime to subtract 1 each second. Then after 10 seconds, randomize the vector and add 10 to the timer.

Then there is the coroutine. Within the coroutine you can make use of “yield return new WaitForSeconds()” to add a delay to your code. You could combine this with a while loop to assign a random vector3 each 10 seconds.

Also there is InvokeRepeating(), I’m not really familiar with this method so I’m not sure how well it will fit in your project, but I know it will keep calling a function for every x-seconds. So this is also a way to go.

I hope this will give you enough information to get you going.