Random.Range Vector3

I’m wondering if there’s a simple way to generate a random Vector3 given maximum and minimum Vector3’s.

So far what I’ve been doing works, but it seems clunky. Is there a better way?

var minPosition : Vector3;
var maxPosition : Vector3;
var randomPosition = Vector3(Random.Range(minPosition.x, maxPosition.x), Random.Range(minPosition.y, maxPosition.y), Random.Range(minPosition.z, maxPosition.z) );

Ideally I’d like to do something like:

var minPosition : Vector3;
var maxPosition : Vector3;
var randomPosition : Vector3 = Random.Range(minPosition, maxPosition);

Is there a better way to find a random value between two Vector3’s?

Your code effectively gives you a random position within a ‘box’, who’s “min” corner is at minPosition and “max” corner is at maxPosition. There’s no handy unity function to return you a random vector within a box unfortunately, however you could of course write your own little utility function to do it. Maybe create a class somewhere called ‘RandomUtils’, with a static function in called ‘RandomVectorInBox’.

The Random.onUnitSphere, or Random.insideUnitSphere functions give you a random vector either on the surface of, or inside, a sphere of radius 1. Even if you then multiple the result by a random number you won’t end up with an even spread and they wouldn’t match the bounds of your box either. Hence I wouldn’t recommend doing something with them.

So the simple answer is no - there isn’t a nicer way of doing it! But you could write your own little utility function to do it to make your code a little cleaner.

The UnityEngine.Random.onUnitSphere return a unit vector3 random;
You can multiply by any value to set a max radius for the sphere resultant;

Vector3 targetRandomPosition = Random.onUnitSphere*radius;

Here is the code if someone is needing it:

using UnityEngine;

public static class MathUtilities
{
    public static void Random(this ref Vector3 myVector, Vector3 min, Vector3 max)
    {
        myVector = new Vector3(UnityEngine.Random.Range(min.x, max.x), UnityEngine.Random.Range(min.y, max.y), UnityEngine.Random.Range(min.z, max.z));
    }
}

You can use it just by having any vector field and calling from it Random(minVector, maxVector)