c# - 无法将 indexing[] 应用于 GameObject 类型的表达式
问题描述
我的场景中有 3 个空的游戏对象,我试图在上面生成对象,我编写了这个脚本,以便在生成对象的生成器之间有一个 RNG 值。
我遇到了一个问题,我不太确定如何解决它
public class Spawns : MonoBehaviour
{
public GameObject SpawnedObject;
public bool StopSpawn = false;
public float SpawnTime;
public float SpawnDelay;
public GameObject[] SpawnPoints;
int Randomint;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnObjects", SpawnTime, SpawnDelay);
}
public void SpawnObjects()
{
Randomint = Random.Range(0, SpawnPoints.Length);
Instantiate(SpawnedObject[Randomint], transform.position, transform.rotation);
if (StopSpawn)
{
CancelInvoke("SpawnObjects");
}
}
}
解决方案
您正在尝试在单个GameObject
引用上使用索引。
由于您使用并遵循您的描述来选择随机值SpawnPoints.Length
,因此您实际上宁愿获取数组的元素SpawnPoints
。
你还说
我的场景中有 3 个空的游戏对象,我试图在上面生成对象
但这不是你的代码会做的。
您可能更想使用
Instantiate(SpawnedObject, transform.position, transform.rotation, SpawnPoints[Randomint].transform);
查看Instantiate
并在您的特定情况下超载
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
第一个参数是original
要生成的预制件/对象,最后一个参数是可选parent
Transform
的生成位置。
您可能还想重新考虑为position
和rotation
.. 提供的值。您真的要在脚本附加到的对象的位置和旋转处生成对象吗?您是否不想让它们在相应生成点的位置和旋转处生成?;)
推荐阅读
- jenkins - 如何在 Jenkins Groovy 脚本中将参数引用为变量
- reactjs - Reactjs Material在TextField中加载defaultValue&无法读取未定义的属性'map'
- javascript - Typescript在没有硬编码的情况下重命名数组中的键?
- dataframe - 使用数据框 pyspark 生成矩阵并填充数据
- reactjs - Facebook 登录引发对 XMLHttpRequest 的访问已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头
- python - 在数据框中,我如何计算特定值,然后选择计数最高的值来创建另一个数据框?
- c# - 无法从“ref System.Array”转换为“ref TBApp.CompanyStruct”
- java - 使用 apache (mod_wsgi) 调用 Django API
- series - 如何使用 cudf.Series.applymap()?
- jquery - 如何在jQuery填充的html元素行中的前一行中排除已选择的下拉值