我试图在游戏中随机初始化游戏对象,但只有当我尝试使用Update()函数中的相同代码实例化游戏对象时,我才在start()函数进行实例化,它显示以下错误消息"NullReferenceException:对象引用未设置为对象的实例"
我的代码如下:
using UnityEngine;
using System.Collections;
public class birdinstantiate : MonoBehaviour {
public GameObject rna;
private float screenWidth;
private float screenHeight;
private Vector3[] pos;
public Transform prefab;
private GameObject[] create;
int i;
Vector3 randompos;
void Start () {
i=0;
screenWidth=Screen.width;
screenHeight=Screen.height;
Vector3[] pos=new Vector3[5] ;
// GameObject[] create=new GameObject[8];
pos[0]=Camera.main.ScreenToWorldPoint(new Vector3(screenWidth*.5f,screenHeight*1.18f,8f));
pos[1]=Camera.main.ScreenToWorldPoint(new Vector3(screenWidth*.2f,screenHeight*1.18f,8f));
pos[2]=Camera.main.ScreenToWorldPoint(new Vector3(screenWidth*.9f,screenHeight*1.18f,8f));
pos[3]=Camera.main.ScreenToWorldPoint(new Vector3(screenWidth*.7f,screenHeight*1.18f,8f));
pos[4]=Camera.main.ScreenToWorldPoint(new Vector3(screenWidth*.65f,screenHeight*1.18f,8f));
Instantiate(rna,new Vector3(pos[Random.Range(0,4)].x,pos[Random.Range(0,4)].y,pos[Random.Range(0,4)].z), Quaternion.identity);
}
void Update () {
Instantiate(rna,new Vector3(pos[Random.Range(0,4)].x,pos[Random.Range(0,4)].y,pos[Random.Range(0,4)].z), transform.rotation) as GameObject;
}
在update()中实例化不起作用。如果有人帮我解决问题,那将非常有帮助
唯一可能为空的是"rna"GameObject,您可能没有从检查器中分配它。
提示:使用随机范围(0,位置长度)或随机范围(0.5)。它返回一个类型为[min,max)的间隔(从min到小于max)。问题:你为什么要在Update()上实例化东西?