So I’m trying to get a function to run from a parent script when I click on an object with a particular tag.
Script A (RayCastHit) is for my raycast and tests if it has hit the particular object while Script B(PickUpReactions) is for reducing a count.
Script B is attached to the parent object while Script A is attached to the child.
using UnityEngine;
using System.Collections;
public class RayCastHit : MonoBehaviour
{
public int PowerAmount = 1;
public float fireRate = 0.25f;
public float weaponRange = 50f;
public Camera MainCam;
public AudioClip ShotsFired;
private float nextFire;
void Start()
{
MainCam = GetComponentInParent<Camera>();
}
void Update()
{
if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Vector3 rayOrigin = MainCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCam.transform.forward, out hit, weaponRange))
{
if (hit.transform.gameObject.tag == "Generator")
{
gameObject.GetComponent<PickUpReactions>().ReduceCount();
AudioSource.PlayClipAtPoint(ShotsFired, transform.position);
}
}
}
}
}
but because of the “gameObject.GetComponent().ReduceCount();” line, it comes up with the error “NullReferenceException: Object reference not set to an instance of an object
RayCastHit.Update () (at Assets/Scripts/RayCastHit.cs:41)”. he other script looks like this.
using UnityEngine;
using System;
using UnityEngine.UI;
using System.Collections;
public class PickUpReactions : MonoBehaviour {
public int count;
void Start () {
count = 0;
}
public void ReduceCount()
{
if (count >= 0)
{
count = count - 1;
}
}
}
I’ve spent hours googling solutions that don’t work yet so I don’t know why they don’t want to talk.