using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomPlace : MonoBehaviour
{
public Transform[] SpawnPoints;//存放生成位置
public GameObject[] prefab;//生成的物体
public float spawnTime = 3f;//多长时间后调用
public float nextSpawnTime = 2f;//下一个物体生成的时间
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnPrefab", spawnTime, nextSpawnTime);
//"SpawnPrefabs" : 调用的方法名称
//spawnTime: 多长时间后调用
//nextSpawnTime: 下一个物体生成的时间
}
private void SpawnPrefab()
{
int Index = Random.Range(0, SpawnPoints.Length);//生成位置数组下标
//随机生成一个数组的下标
Instantiate(prefab, SpawnPoints[Index].position, SpawnPoints[Index].rotation);
//prefab: 生成的物体
//SpawnPoint[Index].position: 生成的物体所在的位置
//SpawnPoint[Index].rotation: 生成物体的角度
}
}
报错的是:Assets\RandomPlace.cs(55,9): error CS0311: The type 'UnityEngine.GameObject[]' cannot be used as type parameter 'T' in the generic type or method 'Object.Instantiate(T, Vector3, Quaternion)'. There is no implicit reference conversion from 'UnityEngine.GameObject[]' to 'UnityEngine.Object'.
这个错误是因为在第 33 行中,你将 prefab 定义为一个 GameObject 类型的数组,但是在第 55 行中,你将 prefab 作为 Object.Instantiate() 方法的第一个参数,但是 Instantiate() 方法的第一个参数需要传递一个 Object 类型的参数,而 GameObject 类型并不能直接转换为 Object 类型,所以导致了这个错误。
要解决这个问题,你只需要将第 55 行的代码修改为下面这样就可以了:
Instantiate(prefab[Index], SpawnPoints[Index].position, SpawnPoints[Index].rotation);
这里的修改将 prefab 数组中的元素从数组中选出来,传递给 Instantiate() 方法,这样就可以正确的生成物体了。
如果对您有帮助,请给与采纳,谢谢。