我在統一問題中看到了這段代碼,但它不能正常作業
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;
}
互聯網上只有 3 個代碼并且無效,它們都以某種方式損壞......有沒有辦法在給定區域隨機生成預制件?
uj5u.com熱心網友回復:
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;
}
}
我已經解決了幾個錯誤并進行了更改:x_dim = plane.size.x;
到這個
x_dim = plane.GetComponent().bounds.size.x;
并且還添加了
x_dim /= 2; z_dim /= 2;
例如,如果平面的長度是 10,我們需要它的一半(10/2=5) 現在我們可以寫: var x_rand = Random.Range(-x_dim, x_dim); 例如:(-5,5)
現在它正在作業。你只需要呼叫 spawn 方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508685.html
