I saw this code in unity questions but it doesn't work properly
public Transform plane;
public GameObject spawnablePrefab;
// Plane Properties
float x_dim;
float z_dim;
void Start () {
// Get the length and width of the plane
x_dim = plane.size.x;
z_dim = plane.size.z;
}
void Spawn () {
// Spawn the object as a child of the plane. This will solve any rotation issues
GameObject obj = Instantiate (spawnablePrefab, Vector3.zero, Qauternion.Identity, plane) as GameObject;
/* Move the object to where you want withing in the dimensions of the plane */
// random the x and z position between bounds
var x_rand = Random.Range(-x_dim, x_dim);
var z_rand = Random.Range(-z_dim, z_dim);
// Random the y position from the smallest bewteen x and z
var z_rand = x_rand > z_rand ? Random.Range(0, z_rand) : Random.Range(0, x_rand);
// Now move the object
// Since the object is a child of the plane it will automatically handle rotational offset
obj.transform.position = new Vector3 (x_rand, y_rand, z_rand);
// Now unassign the parent
obj.parent = null;
}
There are only like 3 codes on the internet and non works, they are all broken in some way... Is There a way to spawn prefabs, randomly in a given area?
CodePudding user response:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSpawner : MonoBehaviour
{
public Transform plane;
public GameObject spawnablePrefab;
// Plane Properties
float x_dim;
float z_dim;
void Start()
{
// Get the length and width of the plane
x_dim = plane.GetComponent<MeshRenderer>().bounds.size.x;
z_dim = plane.GetComponent<MeshRenderer>().bounds.size.z;
x_dim /= 2;
z_dim /= 2;
}
public void Spawn()
{
// Spawn the object as a child of the plane. This will solve any rotation issues
GameObject obj = Instantiate(spawnablePrefab, Vector3.zero,
Quaternion.identity, plane) as GameObject;
/* Move the object to where you want withing in the dimensions of the plane */
// random the x and z position between bounds
var x_rand = Random.Range(-x_dim, x_dim);
var z_rand = Random.Range(-z_dim, z_dim);
// Random the y position from the smallest bewteen x and z
z_rand = x_rand > z_rand ? Random.Range(0, z_rand) : Random.Range(0, x_rand);
// Now move the object
// Since the object is a child of the plane it will automatically handle rotational offset
obj.transform.position = new Vector3(x_rand,0, z_rand);
// Now unassign the parent
obj.transform.parent = null;
}
}
I have solved several errors
and changed:
x_dim = plane.size.x;
to this
x_dim = plane.GetComponent().bounds.size.x;
and also added
x_dim /= 2;
z_dim /= 2;
For example if the length of the plane is 10 we need half of that(10/2=5) Now we can write: var x_rand = Random.Range(-x_dim, x_dim); Ex:(-5,5)
Now it is working. You just need to call the spawn method.