- Home /
Unity 5 Calling Function From Another Script On A Different Object
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.
So PickUpReactions is attached to the parent of RayCastHit?
Yes FPSController (PickUpReactions is here) | ---> Launcher (RayCastHit is here)
gameObject.GetComponent<PickUpReactions>().ReduceCount();
The gameObject here is the game object with the RayCastHit script on it ("The game object this component is attached to.") If I understand your question correctly you want to use:
hit.transform.gameObject.GetComponent<PickUpReactions>().ReduceCount();
Answer by Lilius · Oct 04, 2016 at 06:22 AM
You are trying to find ReduceCount script on the same game object that has RayCastHit script.
Shouldn't this line: gameObject.GetComponent().ReduceCount();
be instead: transform.parent.gameObject.GetComponent().ReduceCount();
Your answer
