Hello, Im currently working on a game and Im trying to avoid writing getComponent<>() every time Im trying to call a function from another script.
So I declared a variable outside of any function Player player; and defined it in the awake function
void awake(){
player = GetComponent<Player>();
}
Player in this case is a script if all the important functions of the game. Both scripts are on the same object. Now every time Im running the game I get a
NullReferenceException: Object reference not set to an instance of an object
The script is pretty long (and a work in progress so its pretty messy) so Im putting it in a pastebin . The line its giving me an error for is 98, but it isn’t the code of this particular function that is giving an error, its just the only one which is called in update().
C# (most programming languages) is case sensitive. So your awake is never called since Unity call Awake. Player is not assigned you get a null reference exception.
When trying to track this stuff down, use Debug.Log() statements everywhere you can think of. If you had one in awake() you’d immediately see that it wasn’t called, so you could pinpoint the problem. It takes awhile to get the hang of fixing errors, and the more complex your games get, the more complex the errors can get…but stick with it! On the plus side, you’ll soon be able to spot (and better yet, avoid altogether) the simpler errors, and you’ll feel more and more fluent with the language.
When you get such errors/exceptions usually the line where it happens is given. You can also double click it in the console so your IDE highlights the line for you. Then you can place Debug.Log statements around there to check your assumptions (variables, code beeing executed at all etc.). This way you could have “approached” the error by yourself. Debugging is at least as important as programming, so learn the methods and tools of doing so. This will make you a much better programmer. And you can’t run to the forums for every error/problem happening to you ;). But it’s good to learn from such mistakes and expand your “portfolio” of things to avoid.
And kudos for using code tags properly in your first post.