- Home /
How do I make onMouseDown work for OnGUI in C#?
Currently I have the js version:
var _mouseDown = false;
function OnGUI() {
if(_mouseDown) {
GUI.Box(Rect(10,10,100,20),"object!");
}
}
function OnMouseDown () {
_mouseDown = true;
}
function OnMouseUp () {
_mouseDown = false;
}
function OnMouseOut() {
_mouseDown = false;
}
However, I can't seem to get the same thing for C#. When I try to rewrite it with void onMouseDown, I get errors. Here is a sample from the reference manual that I want to use but I can't seem to add onMouseDown properly to get it to work.
using UnityEngine;
using System.Collections;
public class TextLabelC : MonoBehaviour {
void OnGUI() {
GUI.Box(new Rect(10, 10, 100, 20), "Object");
}
}
Also, for my above script in js, I am wondering how do I make the label stay on the screen without having to hold and press the mouse down but also, having it disappear when navigating to another object
Answer by YoungDeveloper · Dec 31, 2013 at 05:43 PM
Hi, If i remember correctly you can use Event handler.
if (Event.current.type == EventType.MouseDown){
}
You can even pre save it if you need to use it many times.
Event e = Event.current;
if (e.type == EventType.MouseDown){
}
Error CS1519: Invalid token 'if' in class, struct, or interface member declaration (CS1519) (Assembly-CSharp-firstpass) Error CS1519: Invalid token '==' in class, struct, or interface member declaration (CS1519) (Assembly-CSharp-firstpass) Error CS1519: Invalid token ')' in class, struct, or interface member declaration (CS1519) (Assembly-CSharp-firstpass)
Those are the errors I get with your code.
:D Did you just copied it inside class ? It should be in OnGUI() method.
void OnGUI(){
Event e = Event.current;
if (e.type == EventType.$$anonymous$$ouseDown){
Debug.Log("press");
}
}
Oh I see what you mean but for some reason, I can't seem to get the GUI.Box to show on the screen. Nothing appears when I click.
This will toggle (show and hide) GUI box on mouse press
private bool toggleBox = false;
void OnGUI(){
if(toggleBox)GUI.Box(new Rect(10, 10, 100, 20), "Object");
Event e = Event.current;
if (e.type == EventType.$$anonymous$$ouseDown){
toggleBox = !toggleBox;
}
}
Ins$$anonymous$$d of hard coding the object name, is it possible to assign new labels for each object I click on? (If I moved from Object 1 to Object 2 and I want each label to display different names for each object selected). How would I get started on something like that?
Thank you so much again!! :D
Your answer
Follow this Question
Related Questions
I keep getting an error on my for loop. 1 Answer
Making scrollbar for GUI.Label inside a draggable GUI.Window 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers