嘿伙计们我对团结和编码很新,但我真的试图找出为什么这个脚本不适用。该脚本的想法是应该在X轴上的随机位置上在+9到-9范围内重复产生一个对象,但它只是在对象的起始位置产生一次。希望有人能指出我正确的方向:)
using UnityEngine;
using System.Collections;
public class SpawnOnXaxis : MonoBehaviour {
public GameObject Goodfood;
public int numToSpawn;
public Vector3 position;
void Awake()
{
Vector3 position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, -1); // -9 på Xaxis - +9 ----- Y = 10.5 z = -1
}
void Start()
{
int spawned = 0;
while (spawned < numToSpawn)
{
position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, Random.Range(-9.0F, 9.0F));
GameObject tmp = Instantiate(Goodfood, position, Quaternion.identity) as GameObject; // Quaternion.identity betyder "ingen rotation"
spawned++;
System.Threading.Thread.Sleep(500);
}
}
}
答案 0 :(得分:1)
您没有将numToSpawn设置为任何内容。试试这个:
public class SpawnOnXaxis : MonoBehaviour {
public GameObject Goodfood;
public int numToSpawn;
public Vector3 position;
void Awake()
{
position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, -1); // -9 på Xaxis - +9 ----- Y = 10.5 z = -1
numToSpawn = 10;
}
void Start()
{
int spawned = 0;
while (spawned < numToSpawn)
{
position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, Random.Range(-9.0F, 9.0F));
GameObject tmp = Instantiate(Goodfood, position, Quaternion.identity) as GameObject; // Quaternion.identity betyder "ingen rotation"
spawned++;
System.Threading.Thread.Sleep(500);
}
}
}
答案 1 :(得分:0)
试试这个。 Invoke Reapeating可以解决您的问题。 下面的代码调用CreateObjects 0.3秒。首先是1秒后开始。
public GameObject Goodfood;
public int numToSpawn; //I assume you edit this value in editor
public Vector3 position;
int spawned = 0;
void Start() // or you can use Awake too.
{
InvokeRepeating("CreateObjects", 1, 0.3);
}
void CreateObjects(){
position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, Random.Range(-9.0F, 9.0F));
GameObject tmp = Instantiate(Goodfood, position, Quaternion.identity) as GameObject;
spawned++;
if(spawned>9){
CancelInvoke("CreateObjects");
}
}
如果您不想使用此功能,也许您可以使用Update方法。像
void Update() {
if(spawned<10){
position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, Random.Range(-9.0F, 9.0F));
GameObject tmp = Instantiate(Goodfood, position, Quaternion.identity) as GameObject;
spawned++;
}
}