NullReferenceExeption

Hey guys,

So I’m writing a scrip for a game I’m working on, and I keep getting a NullReferenceExeption. I have been using unity for almost a year, but I still can’t figure it out.

It’s on line 24, the line is “BulletObject.rigidbody.velocity = transform.forward * BulletSpeed;”

using UnityEngine;
using System.Collections;

public class FiringScript : Photon.MonoBehaviour {

	public KeyCode FiringKey = KeyCode.Space;

	public GameObject bullet;

	public GameObject[] FiringPoints;

	public int BulletSpeed = 10;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if(photonView.isMine){
			if (Input.GetKeyDown (KeyCode.Space)) {
				foreach (GameObject point in FiringPoints){
					GameObject BulletObject = PhotonNetwork.Instantiate(bullet.name, point.transform.position, point.transform.rotation, 2);
					BulletObject.rigidbody.velocity = transform.forward * BulletSpeed;
				}
			}
		
		}
		
	}
}

Obviously if your PhotonNetwork.Instantiate(…) function returns null, there will be no object to work with and therefore you can’t access any of it’s properties like .rigidbody and so on.

Just for the sake of good programming style if you encounter any situation in which your object somehow could be null you should check it before accessing any of it’s properties

GameObject BulletObject = PhotonNetwork.Instantiate(bullet.name, point.transform.position, point.transform.rotation, 2);
if(BulletObject != null)
    BulletObject.rigidbody.velocity = transform.forward * BulletSpeed;

Of course there might be a problem with your PhotonNetwork.Instantiate(…) function, you may need to check if it’s called under right circumstances, but you should check if object is null anyway