我在使用C#使用Unity / MonoDevelop进行编码时遇到了一些问题。我想要做的是有30个不同的位置,但是使用随机发生器只有20个这样的位置会产生一个预制件。我正在使用关于产生对象(https://www.youtube.com/watch?v=kTvBRkPTvRY)的Youtube Channel Gamad教程修改脚本。 以下是我现在拥有的: `使用System.Collections; 使用System.Collections.Generic; 使用UnityEngine;
public class SpawnObject:MonoBehaviour { public GameObject BeehivePrefab;
public Vector3 center;
public Vector3 size;
public Quaternion min;
public Quaternion max;
public int spawnCount = 0;
public int maxSpawns = 20;
public GameObject [] selectorArr;
// Use this for initialization
void Start () {
SpawnBeehive ();
}
// Update is called once per frame
void Update () {
while (spawnCount < maxSpawns){
int temp = Random.Range(0, selectorArr.length);
selectorArr[temp].Instantiate;
spawnCount++;
}
}
public void SpawnBeehive(){
Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2),Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));
Instantiate (BeehivePrefab, pos, Quaternion.identity);
}
void OnDrawGizmosSelected(){
Gizmos.color = new Color (1, 0, 0, 0.5f);
Gizmos.DrawCube (transform.localPosition + center, size);
}
}` 在这段代码中,我在第26行和第27行遇到错误(使用int tem和selectorArr的行)。
答案 0 :(得分:1)
之前我从未使用过GameObject.Instantiate函数,我通常只是实例化对象或通过代码更改对象的渲染。但是从文档页面docs.unity3d.com/ScriptReference/Object.Instantiate.html,它似乎允许你克隆一个对象
我对你拥有GameObject Array selectorArr的内容感到有些困惑。
现在,如果它是一个你想要产生的不同对象的数组,你可以用类似的东西来做。
Instantiate(selectorArr[temp], Vector3, Quaternion.identity);
或者如果你想将随机区域保留在一个区域内,你可以用这样的东西重新使用这个函数,然后调用SpawnBeehive(WhatEverGameObjectYouWant)
public void SpawnBeehive(GameObject foobar){
Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2),Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));
Instantiate (foobar, pos, Quaternion.identity);
}