0

I was trying to randomly initialize game object in my game but my instantiate working in start() function only when i try to instantiate gameobject using same code in Update() function it shows following error message " NullReferenceException: Object reference not set to an instance of an object"

my code are given below:

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; 

}

instantiate in the update() not working .It will be very helpful if anyone help me out

Mubir
  • 63
  • 1
  • 8
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeSmile Feb 16 '15 at 10:42

1 Answers1

0

The only thing that could be null there is the "rna" GameObject, which you might have not assigned from the inspector.

Tip: Use Random.Range(0, pos.Length) or Random.Range(0, 5). It returns an interval of type [min, max), (from min to less than max). Question: Why would you Instantiate stuff on Update() ?

Miron Alex
  • 258
  • 1
  • 9