I have a parent object, which is empty except for its script (except below). It has one child, which is a cuboid consisting of a mesh renderer, mesh collider, and mesh filter. I’m making a tile-based game, and the cuboid represents the currently-selected tile. When the player moves the cursor out of the game area, I want the cuboid’s mesh renderer to be disabled, and then be re-enabled when the mouse re-enters the game area.
validSelection is a bool, which detects whether or not the play area is being selected by the user.
The last line throws a NullReferenceException every frame, regardless of mouse position or whether or not the mesh renderer is enabled. Funnily enough, however, my code is working perfectly - the box disappears upon leaving the play area, and reappears on reentry.
Even “childMeshRenderer.enabled” by itself is throwing the NullReferenceException, so I’m sure the issue is with the mesh renderer. There are no other compiler errors. Start() is running, and it doesn’t matter where I initialize childMeshRenderer, or even if I just write
Honestly I’d just set childMeshRenderer to public and assign it in the inspector. That is odd though, the only time GetComponentInChildren will return null is if the component doesn’t exist.
If I were to have a guess at what’s happening, the script is probably attached to another object as well as the one with the box. That would explain why it’s working but still throwing the exception. Click the error once (not double click) and the GameObject that threw the exception will be highlighted in the hierarchy.
I recommend you learn how to debug code. Debugging can be used to find out what is causing this error. Being able to debug an application is an essential tool for programmers.
Unity features the following video in their Tutorials section, that should provide the basic steps needed to debug your problem:
@Freecell I agree with @Scabbage if your code is working but you are getting a null reference, you probably have a second copy of the script that is throwing the error in your scene. You can search for scripts several ways, including just right clicking on the script in your project window and choosing find references in scene.