- Home /
Object reference not set to an instance of an object
Hello,
I'm quite new to programming and I've been trying to make a waypoint system for my game so my units can move from place a to b through waypoints, here are my 2 scripts I've made.
This is my unit Script
using UnityEngine;
using System.Collections;
public class Unit: MonoBehaviour
{
public int next = 1;
public float speed = 10.0f;
Transform destination;
void Update ()
{
Waypoint asd = findNextTarget ();
setDestination (asd.transform);
float stepSize = Time.deltaTime * speed;
transform.position = Vector3.MoveTowards (transform.position, destination.position, stepSize);
if (transform.position.Equals (destination.position)) {
if (next == 6) {
Destroy (gameObject);
}
next++;
}
}
Waypoint findNextTarget ()
{
Waypoint b = null;
Waypoint[] petes = (Waypoint[])FindObjectsOfType (typeof(Waypoint));
for (int i = 1; i < petes.Length; ++i) {
if (petes [i].wp == next) {
b = petes [i];
}
}
return b;
}
public void setDestination (Transform v)
{
destination = v;
}
}
and this is my Waypoint script:
using UnityEngine;
using System.Collections;
public class Waypoint : MonoBehaviour
{
public int wp = 1;
}
When I'm trying to run a project I get this error: Object reference not set to an instance of an object. It refers to line 15 of my unit code.
I've attached the unit code to a cube gameobject and waypoint script to 6 different sphere objects.
I've set the next variable to 1 for the Unit and I've set wp to 1,2,3,4,5 and 6 to each 6 sphere objects.
Thanks in advance, I just can't figure out what's wrong.
Could you copy and paste all your Errors that you see in the console please. Do not paraphrase them.
NullReferenceException: Object reference not set to an instance of an object Unit.Update () (at Assets/Unit.cs:15)
This is the error that I'm getting
Answer by mattyman174 · Mar 20, 2014 at 11:01 AM
if (next == 6) {
Destroy (gameObject);
}
next++;
Change to:
if (next < 6) { // Changed == to <
Destroy (gameObject);
}
next++;
Yep i see now. $$anonymous$$eep that code block the same (so next == 6)
In your findNextTarget() function, you need to initialise your i variable in your for loop to equal 0, not 1.
As such.
for (int i = 0; i < petes.Length; i++) // Notice int i = 0 (not 1)
{
if (petes[i].wp == next)
{
b = petes[i];
}
}
Try that.
Also, as an Edit i just noticed, unless you intentionally tried to Pre Increment your i variable, i suggest you stick with Post Increment as i have done above. Unless you understand the consequences of such actions just stick with Post increment.