Home > Enterprise >  How can I spawn objects in a given volume/area 3d
How can I spawn objects in a given volume/area 3d

Time:03-08

I was given a task by my teacher to make a script to spawn object RANDOMLY in a given AREA 3D, I know how to just like that but have no idea if randomly in the given radius, please help :(.

Thanks.

CodePudding user response:

Measure the range (x-axis, y-axis, z-axis) in Unity, and then use time to control how often it is generated. These are randomly generated codes, don't forget to drag the prefab to the cube

public GameObject cube;//Define a cube to store the prefab to be randomly generated
private float t1, t2;// Control how often to generate by time

void Start()
{
    t1 = 0;//time when the game starts
}

void Update()
{
    t2 = Time.fixedTime;//The time when the game progresses to a certain position
    if (t2 - t1 >= 2)
    {
        x = Random.Range(-50,50);//Specify the range in the x-axis direction
        z = Random.Range(-50,50);//Specify the range in the z-axis direction
        //Specify the scope according to the actual situation of your own scene
        Instantiate(cube, new Vector3(x, 0.5f, z), Quaternion.identity);// Randomly generate objects (prefab, generated position, orientation).
        t1 = t2;//Every time it is generated, let t1=t2

    }
}
  • Related