I have a game object named Hitbox with a child named feet. On Hitbox is a script called Walking and on feet is one called Feetcollide. Walking has a variable (int) named grounded. Feetcollide looks like this.
using UnityEngine;
using System.Collections;
public class FeetCollide : MonoBehaviour
{
void OnCollisionEnter ()
{
transform.Find("Hitbox").GetComponent<Walking>().grounded= 1;
}
void OnCollisionExit ()
{
transform.Find("Hitbox").GetComponent<Walking>().grounded = 0;
}
}
When I run this code I get a NullReferenceExeption, and the variable never changes.
If I’m understanding the hierarchy correctly, the call to tranform.Find is only looking at children of that transform, and Hitbox is the parent.
As long as the parent/child relationship is constant, you should be able to use transform.parent.GetComponent()…
Also, it would be a good idea to establish this relationship in the Start function rather than making the calls to transform.parent and GetComponent each frame.
Declare a variable to hold the transform, then set it it in Start, and reference the variable instead.
e.g.
public class FeetCollide : MonoBehaviour
{
Walking walking;
void Start()
{
walking = transform.parent.GetComponent<Walking>();
}
void OnCollisionEnter ()
{
walking.grounded= 1;
}
...
Transform.Find() finds a child of the Transform you are calling it on. Feet has no children called Hitbox, so you get a NullReferenceException error.
Try using:
transform.parent.GetComponent<Walking>()
instead of:
transform.Find("Hitbox").GetComponent<Walking>()