GetComponnent null reference C#
My PlayerController script has a variable public bool grouned variable that attached to Player. In the other game object, I want to get information from PlayerController.grounded script but when running the game, it show error message with null reference.
PlayerController _myPlayer;
void Start (){
_myPlayer = GetComponent<PlayerController>();
}
void Update(){
if(_myPlayer.grounded)
//Do_something
}
Don't post nullreference exceptions here, they are asked and answered hundreds of times. They are also well documented.
If you run into any sort of compiler error (an error that has an error number like CS1015) or any exceptions, google them. This saves you time and also helps avoid useless questions.
If you are unsure what to post on UA, check out the FAQ and user guide.
Have a nice day, try to be a little more independent and research your questions. :)
Answer by wojtask12 · Jun 11, 2016 at 10:03 PM
GetComponent function tries to get the component attached to the same game object it's called from (so the same object your script is attached to). Istead, you can use, among others, FindObjectOfType<PlayerController>()
function to get your PlayerController instance