So for some reason when I play the game and hit nothing, I get this error in my script:
NullReferenceException: Object reference not set to an instance of an object
DetectClick.Update () (at Assets/Scripts/Game/DetectClick.cs:34)
Referring to the line in the script:
if (hit.collider.tag == “Girl”) {
my objects are tagged properly and I even tried changing the line to"
if ((hit.collider.tag != null) && (hit.collider.tag == “Girl”)) {
as suggested in another thread but that doesn’t work either. Here’s my full script:
using System.Collections.Generic;
using UnityEngine;
public class DetectClick : MonoBehaviour {
public GameObject blood;
public bool gWarning;
private AudioSource audi;
public AudioClip shot;
public AudioClip empty;
public AudioClip reload;
// Use this for initialization
void Start () {
audi = this.gameObject.GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonUp (0) && ScoreKeep.gunClip >= 1) {
audi.PlayOneShot (shot, 0.5f);
ScoreKeep.gunClip -= 1;
Vector3 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector2 mousePos2D = new Vector2 (mousePos.x, mousePos.y);
RaycastHit2D hit = Physics2D.Raycast (mousePos2D, Vector2.zero);
if (hit.collider.tag == "Girl") {
ScoreKeep.livesLeft -= 1;
gWarning = true;
Instantiate (blood, hit.collider.transform.position, hit.collider.transform.rotation);
Destroy (hit.collider.gameObject);
}
if (hit.collider.tag == "Zombie") {
ScoreKeep.zombieKills += 100;
Instantiate (blood, hit.collider.transform.position, hit.collider.transform.rotation);
Destroy (hit.collider.gameObject);
}
}
if (Input.GetMouseButtonUp (0) && ScoreKeep.gunClip <= 0) {
audi.PlayOneShot (empty);
}
if (Input.GetMouseButtonUp (1) && ScoreKeep.gunClip <= 0) {
audi.PlayOneShot (reload);
ScoreKeep.gunClip += 10;
}
}
}
Any and all help is greatly appreciated. I’ve been trying to wrap my head around this for a few days now and can’t seem to fix the error. Thank you!