- Home /
Differentiate on click anywhere vs click on button...
Hi guys,
In my game I want an object being turned off when a click is being pressed down, and then re-activated when mouse click is released... like the below
if (Input.GetMouseButtonDown (0)) {
centerPiece.SetActive (false);
}
if (Input.GetMouseButtonUp (0)) {
centerPiece.SetActive (true);
}
This part is okay but the problem is when I click my pause button it obviously turns on, and off the game object when I click the button, which I don't wan't to happen...
Any wiser alternatives to approaching this goal, or is there a function to differentiate a click on everywhere else, but the button?
The button was created on a Canvas and is a child of a canvas, not script built.
I'm still a noob so be patient and nice please ;)
Answer by jdean300 · Jun 26, 2016 at 06:08 AM
This could help you out - it's a function I found somewhere that tells you whether or not the pointer is over a UI object:
private bool IsPointerOverUIObject()
{
var eventDataCurrentPosition = new PointerEventData(EventSystem.current)
{
position = new Vector2(Input.mousePosition.x, Input.mousePosition.y)
};
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count > 0;
}
Now you can do something like:
if (Input.GetMouseButtonDown (0) && !IsPointerOverUIObject())
{
centerPiece.SetActive (false);
}
if (Input.GetMouseButtonUp (0) && !IsPointerOverUIObject())
{
centerPiece.SetActive (true);
}
arg.... Didn't want to be a pain and ask evrey little bit.... but does translating that into c# become something like:
private bool pointerCurrent(){
PointerEventData ped = new PointerEventData (EventSystem.current);
List<RaycastResult> rr = new List<RaycastResult> ();
EventSystem.current.RaycastAll (ped, rr);
return rr.Count > 0;
}
Although I'm probably wrong since it's not working XD
Bah... my bad... When I initially dived into unity thought anything that assigns variables with "var" in the front was javascript.... and this worked like charm thanks man
when i add the script i get 4 errors: The type or namespace name 'PointerEventData' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS0246) The name 'EventSystem' does not exist in the current context [Assembly-CSharp]csharp(CS0103) The type or namespace name 'RaycastResult' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS0246)
@samvilm Try including using UnityEngine.EventSystems;
and using System.Collections.Generic;
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Button's sprite swap works fine but it doesn't change the related image's source image! why? 1 Answer
Key for GUI.Button 2 Answers
On off game objects 1 Answer