Duplicate Question
How do I access the collider of a child object through a script on the another object?
I get an error saying "object reference not set to an instance of an object"
,The Parent Object is a Mole, The mole has 3 child objects (1) Hips (2) Body (3) Hair. The collider(and rigidbody) Is on the "Hips" child object. The Script is an Input Script For detecting "Hits on the Mole".
This is The script am using to detect Input.
public class Game_InputManager : MonoBehaviour {
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit; //record input
if (Physics.Raycast(ray, out hit)) // if we are hiitting something what are we hiiting
{
if (hit.collider.tag == "Mole") //if it only hits the gameobject with the mole tag go forward
{
Game_MoleBehaviourmole=hit.collider.gameObject.GetComponent<Game_MoleBehaviour>();
mole.SwitchCollider(0);
mole.anim.SetTrigger("hit");
Debug.Log(hit.collider.gameObject + "got hit");
}
}
}
}
}
I get this error when I compile it : Object reference not set to an instance of an object.
Hey there, can you add the line of your error message? But i guess it should be something in line 14 where you write Game_$$anonymous$$oleBehaviourmole = ...
It should probably say: Game_$$anonymous$$oleBehaviour mole = ...
Let me know if that helps or provide more information please.
Game_$$anonymous$$oleBehaviour mole is written as Game_$$anonymous$$oleBehaviour mole in my code. I made that mistake while copying and pasting it.
This is the error line NullReferenceException: Object reference not set to an instance of an object Game_Input$$anonymous$$anager.Update () (at Assets/Game_Input$$anonymous$$anager.cs:28)
[Line 28 is mole.SwitchCollider(0);]
is the Game_$$anonymous$$oleBehaviour
on the same transform as the collider you are hitting? this error implies that mole
equals to null
so in other words the requested component was not found.
Perhaps a Debug.Log(hit.transform.name);
might help you figure this out.
Use Debug.Log( hit.collider.transform, hit.collider.transform );
to check which object has been hit. Then, use the parent
and GetChild
to access the desired object.
FAQ :
Some reasons for getting a post rejected:
Posting about a specific compiling error or NullReferenceException: there is a myriad of these questions with answers already, have a look at those posts to get hints on what could possibly be your issue. Also, take a look at the Unity's support website, many errors and how to solve them are described here