c# Object reference not set to an instance of an object
using UnityEngine;
using System.Collections;
public class enemy_movement : MonoBehaviour {
int i=0;
int num=-1;
int temp;
public Transform[] patrolpoints;
public Transform planetposition;
public int movespeed;
private int currentposition;
public int size;
GameObject[] enemy;
GameObject PreFab;
// Use this for initialization
void Start () {
PreFab=(GameObject)Instantiate(Resources.Load("enemy"));
//currentposition=0;
}
// Update is called once per frame
void Update () {
if(num<2)
{
num=num+1;
temp=random_value();
//this is the error line
enemy[num] = (GameObject)GameObject.Instantiate(PreFab, patrolpoints[temp].position, Quaternion.identity);
}
for(i=0;i<=num;i++)
enemy[i].transform.position=Vector3.MoveTowards(enemy[i].transform.position, planetposition.position , movespeed*Time.deltaTime);
}
int random_value()
{
int num = Random.Range(0, patrolpoints.Length);
return num;
}
}
i'm new to c#,building my first game on unity.
the error that i get is NullReferenceException: Object reference not set to an instance of an object (wrapper stelemref) object:stelemref (object,intptr,object) enemy_movement.Update () (at Assets/scripts/enemy_movement.cs:50)
this code works for a single enemy ,but not for multiple that are created using an array. any way to correct this or any better way to do this.
thanks.
You don't need to use Resources in order to Load a prefab. You can assign prefabs by clicking and dragging them onto the component's public variable in the editor.
Ensure that the variable is public.
thanks for your reply, i did what you said, but still the same error.
Answer by Jessespike · Apr 08, 2016 at 08:20 PM
There's an uninitialized array.
GameObject[] enemy;
change it to something like:
GameObject[] enemy = new GameObject[3];
hey thanks , it is working now. really appreciate your help.
but what if my game could run for a very long time and then the enemies could be very large in number,how do i handle that, how to declare a dynamic array?