NullReferenceException

Hi there,

Im working on a runner game to familiarize myself with unity,
right now I have two spawn points tSpawn and bSpawn. Obstacles will spawn randomly on either of these two objects.

My goal is that I’m trying to translate them toward the player after instantiating so the player will have to jump over or duck under the obstacles.

Currently I have getting a NullReferenceException error on lines 37 and 43 (The lines that attempt to translate the Instances)
So the objects spawn, yet it tells me there is no reference to the objects?? so ofcourse if there’s no reference then no translation occurs, these obstacles just spawn and then don’t move.

My other question has to do with variable types.

“prefab” is of type GameObject, topInstance and BottomInstance are of type GameObject. Yet if I do not have “as GameObject” at the end of lines 36 and 42, then I get an error stating “cannot implicitly convert type from Object to GameObject.”
The funny thing is, “as GameObject” will get rid of this error, but type casting via (GameObject) does not, aren’t they supposed to do the same thing??

Anyway I mimicked this Instantiation code from
http://www.unity3dstudent.com/2010/07/beginner-b05-instantiate-to-create-objects/
Which is this below

//Simple Instantiation of a Prefab at Start
var thePrefab : GameObject;
 
function Start () {
 var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);

I have the same thing as them, my prefab is a GameObject and so are my instances, but yet I get the error about implicitly converting. This doesn’t make sense!?

Here is my source below!

using UnityEngine;
using System.Collections;

public class ObstacleManager : MonoBehaviour 
{
	public GameObject tSpawn;
	public GameObject bSpawn;
	public GameObject prefab;
	public float moveSpeed;
	//private GameObject topInstance, bottomInstance;
	//public float survivalTime;

	// Use this for initialization
	void Start () 
	{
		tSpawn = GameObject.Find("tSpawn");
		bSpawn = GameObject.Find("bSpawn");
	}
	
	// Update is called once per frame
	void Update () 
	{
		Spawn();
	}
	
	void Spawn()
	{
		GameObject topInstance, bottomInstance;
		int[] choice = {0,1};
		int topOrBottom = Random.Range(0, choice.Length);
		Debug.Log("Choice :" + topOrBottom);
		
		if(topOrBottom == 0)
		{
			Debug.Log("TOP Spawned");
			topInstance = Instantiate(prefab, tSpawn.transform.position, tSpawn.transform.rotation) as GameObject;
			topInstance.transform.Translate(-moveSpeed *Time.deltaTime, 0f, 0f);
		}
		else
		{
			Debug.Log("BOTTOM Spawned");
			bottomInstance = Instantiate(prefab, bSpawn.transform.position, bSpawn.transform.rotation)as GameObject;
			bottomInstance.transform.Translate(-moveSpeed * Time.deltaTime, 0f, 0f);
		}
	}
}

So essentially what im trying to do is Translate the objects toward the player.
In trying to do so, I ran into a few problems and raised some questions along the way.

This is probably a really simple fix, I’m so tired its 3 am here, probably the cause for my errors…

Thanks in advanced guys!

how did you “fill” the prefab variable? by dragging something from the hierarchy into the field in the inspector? I suspect doing it that way is putting a transform into that field and not a gameObject… might want to put some debug code into the start function to check the type of the prefab to check if thats the case.

Personally I use transforms for prefab types and it doesn’t have an issue and still works.

edit: oh and you’d get a null pointer if it’s the instance is a transform because you’re calling .transform rather than .transform

prefab was filled just the way you mentioned, I dragged the prefab from my prefabs folder in the project pane into the prefab slot under the inspector.

This is very odd… I changed prefab to be of type transform, and it made the conversion error go away. Sure wasn’t working last night. Maybe I was too tired? lol

My instances, topInstance and bottomInstance, are both of type GameObject. then on lines 37 and 43 (where im getting the NullPtr error) I try to access said gameobjects transform. So I’m either misunderstanding what you mean, or maybe you over looked something in my code?

xD This is bugging me!

From your coding,it look like you are creating Object every frame which is weird…

Yes. An object is being created every frame, however this is currently not an actual problem, I will fix and implement a spawn timer. The real problem here is the NullPtr exception I keep getting.

My guess would be on the fact the spawns are null.

Change your start method to this:

    void Start()
    {
        tSpawn = GameObject.Find("tSpawn");
        bSpawn = GameObject.Find("bSpawn");
        Debug.Log(string.Format("tSpawn is null ? {0}, bSpawn is null ? {1}", tSpawn == null, bSpawn == null));
    }

If they both return true, then that will be your problem.

They both return false. But I was verifying this even before you implemented this Debug.log. I would look at Tspawn and Bspawn in the inspector and I could verify and see that it is in fact finding the objects.

On another note, the objects are actually being spawned randomly, they just aren’t being translated anywhere :confused:

That’t not true. If you feel like it, you can call transform.transform.transform.transform without getting a null reference exception. Though the result is the same as calling transform only, but it works!

Another issue could be that your prefab contains a script with an Awake or OnEnable function, which immediately deletes itself sometimes. Like that you try to access a game object that was just destroyed and you get a null reference exception.

Incase anyone is interested, I went about this a much much simpler way.

Someone on the unity subreddit forum helped me out.

here’s what I did

(Just C&P’d from reddit )

GuideZ (below) helped me figure it out, Incase anyone is interested here’s what I did.
In the scene, I have an empty game object called obstacleManager this has a Script called SpawnManager.cs

using UnityEngine; using System.Collections;
public class SpawnManager : MonoBehaviour { public GameObject tSpawn = null; public GameObject bSpawn = null; public Spawner tScript = null; public Spawner bScript = null;
// Use this for initialization
void Start () 
{
    tSpawn = GameObject.Find("tSpawn");
    bSpawn = GameObject.Find("bSpawn");
}

// Update is called once per frame
void Update () 
{
    int[] choice = {0,1};
    int topOrBottom = Random.Range(0, choice.Length);
    Debug.Log("Choice: " + topOrBottom);
    if(topOrBottom == 0)
    {
        bScript.SpawnObstacle();
    }
    else
    {
        tScript.SpawnObstacle();
    }
}
}

as you can see it has 4 fields, the top spawn, bottom spawn, top spawn script and bottom spawn script. top spawn and bottom spawn are two empty game objects just used for their transformations on where to spawn the obstacles based off of the random value generator I have in the SpawnManagers Update function.
Next it has 2 scripts (both of which are the same Spawner script but on different spawn objects) These are of type Spawner, (the script on the Spawn Objects)
Next is my Spawner.cs script
This is literally all it consists of, just a public GameObject prefab to spawn and then the instantiate public class Spawner : MonoBehaviour { public GameObject prefab;
// Use this for initialization

void Start () 
{
    //prefab=GameObject.Find("Obstacle");
}

// Update is called once per frame
void Update () 
{
}

public void SpawnObstacle()
{
    Instantiate(prefab, transform.position, Quaternion.identity);
}
}

Finally the actual obstacle prefab its self just has a simple translate

    transform.Translate(-moveSpeed* Time.deltaTime, 0f,0f);

negative because it moves towards the player.
Thanks everyone that helped :slight_smile:

*edit for my own sake I do not format my curly brackets like that xD… the format was lost when copy/pasting :P, I also indent alot more haha.