- Home /
NullReference Exception when adding a class
Hello everyone. I'm developing a shooting game with different types of bullets (pressing 1, 2, 3 and 4 will change them). I have a BasicBullet.cs which is like this
using UnityEngine;
using System.Collections;
public class BasicBullet : MonoBehaviour
{
public float speed = 5.0f;
public float DestroyTime = 10.0f;
public Vector3 velocity;
public void changeVelocity(Vector3 v)
{
velocity = v;
}
void Start ()
{
Destroy (gameObject, DestroyTime);
}
void FixedUpdate ()
{
// TO DO
transform.position += velocity * Time.deltaTime;
}
}
And my second bullet is like this using UnityEngine; using System.Collections;
public class Bullet2 : MonoBehaviour {
public float speed = 5.0f;
public float DestroyTime = 10.0f;
public Vector3 velocity;
public void changeVelocity(Vector3 v)
{
velocity = v;
}
void Start ()
{
Destroy (gameObject, DestroyTime);
}
void FixedUpdate ()
{
// TO DO
transform.position += velocity * Time.deltaTime;
}
}
which basically are the same, just for tests purposes. Now, in my player shooting part, this is the code that I have
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour
{
public AudioClip shootAudio;
private AudioSource audioSource;
public GameObject bulletPrefab;
public GameObject fireParticle;
public float fireRate = 0.1f;
private float nextFire = 0.0f;
private bool shooting = false;
private int gunMode = 1;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
//use mouse to fire
if (Input.GetButtonDown ("Fire1"))
shooting = true;
if (Input.GetButtonUp ("Fire1"))
shooting = false;
//use keyboard to change gun type
if (Input.GetKey("1"))
gunMode = 1;
else if(Input.GetKey("2"))
gunMode = 2;
else if(Input.GetKey("3"))
gunMode = 3;
else if(Input.GetKey("4"))
gunMode = 4;
if (shooting)
{
if(gunMode == 1 && Time.time > nextFire)
{
fireParticle.SetActive(false);
audioSource.PlayOneShot(shootAudio);
GameObject bullet = (GameObject)Instantiate(bulletPrefab,this.transform.position + this.transform.forward + this.transform.up, Quaternion.identity);
BasicBullet bulletComp = bullet.GetComponent<BasicBullet>();
bulletComp.changeVelocity(this.transform.forward * 10f);
nextFire = Time.time + fireRate;
}
else if(gunMode == 2)
{
fireParticle.SetActive(true);
}
//TO DO
else if(gunMode == 3 && Time.time > nextFire)
{
fireParticle.SetActive(false);
audioSource.PlayOneShot(shootAudio);
GameObject bullet = (GameObject)Instantiate(bulletPrefab,this.transform.position + this.transform.forward + this.transform.up, Quaternion.identity);
Bullet2 bulletComp = bullet.GetComponent<Bullet2>(); //<----PROBLEM!!!
bulletComp.changeVelocity(this.transform.forward * 10f);
nextFire = Time.time + fireRate;
}
else if(gunMode == 4)
{
}
}
else
{
if(gunMode == 2)
{
fireParticle.SetActive(false);
}
}
}
void OnTriggerStay(Collider other)
{
//for Flamethrower
if(gunMode == 2)
{
if (other.attachedRigidbody)
other.attachedRigidbody.AddForce(this.transform.forward * 50f);
}
}
}
but I get a NullReferenceException in here
Bullet2 bulletComp = bullet.GetComponent<Bullet2>();
bulletComp.changeVelocity(this.transform.forward * 10f);
nextFire = Time.time + fireRate;
What is the problem? Can anyone help me? Thanks! The error is this one:
NullReferenceException: Object reference not set to an instance of an object
Shoot.Update () (at Assets/Scripts/Player/Shoot.cs:65)
Answer by raimon.massanet · Nov 27, 2013 at 09:34 AM
You are instantiating the same prefab (`bulletPrefab`) in both cases. Is that intended behavior? If the prefab does not contain a Bullet2
script, GetComponent
will return null, and you will get a NullReferenceException
.
Answer by Komak57 · Nov 27, 2013 at 10:48 AM
It looks like you're trying to create a bullet object, but grabbing a component script. Bad form. First, generate a GameObject called BulletA, and attach Bullet1 to it. Next, generate a GameObject called BulletB, and attach Bullet2 to it. Drag them to your prefabs folder and delete it from your scene. Next, add a public GameObject bullet; to your Shoot script. This will allow you to drag-and-drop your BulletA or BulletB prefab as the designated item. In the case you want to spawn both bullets, create 2 public GameObject bullet_a, bullet_b; handles. Now, when you've decided this object should spawn, do something like this:
GameObject bullet = (GameObject) GameObject.Instantiate(bullet_a, transform.position, transform.forward);
That's a temporary handle to a freshly spawned copy of bullet_a summoned at the parent scripts position, pointing forward in the parents direction.
From here, you can either throw the bullet by initial velocity, or raycast-teleport inside the Bullet1 script. Remember to destroy the bullet (preferably within it's script) when it is deemed obsolete (out of game bound, collided, traveled for X seconds or meters).
This guy will get you going with tutorials and visual aids: ETeeskiTutorials(Youtube)
Your answer
Follow this Question
Related Questions
How to instantiate object onto other object from script 1 Answer
The infamous: Object Reference not set to an instance of an object 1 Answer
Instantiate a COMPLETELY Unique Instance of an Object 1 Answer
" NullReferenceException: Object reference not set to an instance of an object" 3 Answers
NullReferenceException Error 1 Answer