- Home /
How to whrite in c# the code: onMouseEnter Hide mesh
Hi, I Am writing a code in c# here is what I have at the moment
using UnityEngine; using System.Collections;
public class MouseOver1 : MonoBehaviour {
void OnMouseEnter(){
renderer.enabled = false;
}
void OnMouseExit(){
renderer.enabled = true;
}
}
Im recieving those 2 errors when using the mouse over the cube
NullReferenceException: Object reference not set to an instance of an object MouseOver1.OnMouseEnter () (at Assets/MouseOver1.cs:7) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32, Int32)
NullReferenceException: Object reference not set to an instance of an object MouseOver1.OnMouseExit () (at Assets/MouseOver1.cs:11) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32, Int32)
The code is indeed attached to the cube or what ever else I try with and the object has a collider. I do not understand what is missing thank you for helping me I am really stuck and I am only at the 1st lines of script in my game :S
Your script works fine for me. I attached it to a cube in a new scene. I imagine you would get this error if you attached it to an empty game object...or any game object without a $$anonymous$$eshRenderer component.
Answer by RyanZimmerman87 · Apr 05, 2014 at 02:49 AM
Hmm well surprisingly I still haven't used OnMouseEnter or OnMouseExit even after working with Unity so long... For some reason I thought it was just for GUI stuff but it also says collider in the documentation and it does seem to recognize your commands based on your null reference it just isn't getting access to the object renderer.
You should try creating a game variable like this:
GameObject cubeObject;
void Start()
{
cubeObject = gameObject;
}
void OnMouseEnter()
{
cubeObject.renderer.enabled = false;
}
That should solve your problem based on the null reference error. Normally I don't think you would need the Game Object variable right in the script though if the script is already on that game object... something seems strange here. Maybe it's something to do with OnMouseEnter. Have you tried just enabling and disabling the renderer with other methods like a timer instead of OnMouseEnter?
Do any other objects in your scene have that OnMouseEnter() in their scripts?
Works perfectly thancks for the feedback, I was indeed thinking that I need to specify the target to renderer but wasn't sure of it. I can now proceed to creating the On$$anonymous$$ouseDown fonction :P
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
2D project - player respawn delay problem 0 Answers
An OS design issue: File types associated with their appropriate programs 1 Answer
Do I need a helper class? 2 Answers