Getting Error NullReferenceException but the value I am using is not null?

I’m having a major problem with my code. I have a variable, buttonObject, which is being imported to my DefenderSpawner.cs from Button.cs script correctly. This variable contains the object that should be spawned. Using the Print function, I’ve found that buttonObject is not null and is never altered. However, the error pops up when I try to add my little guys to the Core Game. For anyone who tries to help out, I believe most of the problem lies within the Button.cs script (which is why I included a large portion of Button.cs), but I can’t quite figure this out. Anyone have any tips for me? I’d like the problem explained.

void OnMouseDown(){
		Vector2 mousePos = SnapToGrid(wpMouseClick ()); //makes a variable that is wpMouseClick snapped to grid
 		Instantiate (button.buttonObject, mousePos, Quaternion.identity); //instantiates the selected object at the mousePos converted to actually use game units and is rounded
	}
public class Button : MonoBehaviour {

 
	private Button[] buttonArray;
	public GameObject buttonObject;
	// Use this for initialization
	void Start(){ 
		buttonArray = GameObject.FindObjectsOfType<Button>();
	}

	void Update(){
		print (buttonObject);
 
	}
	void OnMouseDown () {
		Renderer renderer = gameObject.GetComponent<Renderer>(); //on   click, set material to clear

		foreach (Button selectedButton in buttonArray){
			selectedButton.GetComponent<SpriteRenderer>().color = Color.black; //sets all to black
		}
		GetComponent<SpriteRenderer> ().color = Color.white;
 		print (buttonObject);
	}
}

Hi Bill,

Can you perhaps post where the error is occurring, e.g. the line number, and then post the full script which corresponds to that error.

If the top code example is from DefenderSpawner.cs (?), it could be that button is the thing which is null, but again, without the error message and full script(s) it’s very difficult to tell.

Thanks for responding, Rob. I’ve added the logs according to your advice.
The error occurs on line 15 of the DefenderSpawner.cs script, when I try to use button.buttonObject.
I’ve checked using the print method, this value never is set to null. I’ve uploaded the printed output, it shows that the object to be spawned (button.buttonObject) is not null; however, when the Instantiate function is told to call button.buttonObject and spawn it, I receive an error.

error

using UnityEngine;
using System.Collections;

public class DefenderSpawner : MonoBehaviour {
	private Camera camera;
	private Button button;

	void Start(){
		camera = Camera.main;
		button = gameObject.GetComponent<Button>();
	}
 
	void OnMouseDown(){
		Vector2 mousePos = SnapToGrid(wpMouseClick ()); //makes a variable that is wpMouseClick snapped to grid
 		Instantiate (button.buttonObject, mousePos, Quaternion.identity); //instantiates the selected object at the mousePos converted to actually use game units and is rounded
	}

	Vector2 wpMouseClick(){ //world point mouse click
		float mouseX = Input.mousePosition.x;
		float mouseY = Input.mousePosition.y; //makes mouse X and Y
		float distanceFromCamera = 10f; // distance, DUH. if you need a comment for this you're mental
		Vector3 weirdTriplet = new Vector3 (mouseX, mouseY, distanceFromCamera); // a vector3 containing the mouse positions and the distance
		Vector2 worldPos = camera.ScreenToWorldPoint (weirdTriplet); //converts weirdTriplet (which contains the mouse position and the distance from camera) into gmae units
		return worldPos; // returns worldpos
	}

	Vector2 SnapToGrid(Vector2 pos){
		float newX = Mathf.RoundToInt (pos.x);// rounds the stuff up to snap the coords to a grid
		float newY = Mathf.RoundToInt (pos.y); // this does not return a vector converted to the worldpoint, it only rounds it up. this is then used at On Mouse Down to snap to grid

		return new Vector2 (newX, newY );
	}

	 
}

Hi Bill,

Thanks for the additional details.

Ok, so the error is definitely pointing to this line of code;

Instantiate (button.buttonObject, mousePos, Quaternion.identity);

There are three potential candidates there;

  • button.buttonObject
  • mousePos
  • Quaternion.identity

The last can be ruled out as it’s a static as doesn’t required an instance of an object.
mousePos you have declared and initialised in the line above, even if the values for newX and newY in SnapToGrid were zero, you’d get a Vector2 back.

That just leaves button.buttonObject.

Now, button could be null and/or buttonObject could be null, it’s going to be one of them.

The first place I would be checking here would be in your Start method, you use GetComponent<Button>() to grab the component, so checking this is straight forward;

void Start()
{
    camera = Camera.main;
    button = gameObject.GetComponent<Button>();

    if(button != null)
    {
        Debug.Log("I have a button component!");
    }
    else
    {
        Debug.Log("No button component for me!");
    }
}

Pop that in and run the game, which message do you see?

Assuming it finds the Button component, then the only thing remaining is the buttonObject that you are exposing via the Button component. As you have that set up in the Button.cs script as a public GameObject and there isn’t any code looking for it, I’m assuming that you have dragged the relevant object to this exposed field in the script? If not, you’ll need to.

If you have done this, and the message above is finding the component, then please zip the project files up and share them with me and I’ll take a quick look for you.

The forum will allow uploads of up to 10MB, if your project files (zipped) are larger than that you would need to use a service such as Google Drive or Dropbox, and then share the URL.

Hope this helps :slight_smile:

Privacy & Terms