首页 > 解决方案 > 无法将 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");
    }
}
}

标签: c#unity3d

解决方案


您正在尝试在单个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的生成位置。

您可能还想重新考虑为positionrotation.. 提供的值。您真的要在脚本附加到的对象的位置和旋转处生成对象吗?您是否不想让它们在相应生成点的位置和旋转处生成?;)


推荐阅读