- Home /
The question is answered, right answer was accepted
Graphic raycast doesn't return true when clicking on the image
I want to set a boolean variable to true when clicking on the image (like selecting it) but it doesn't return true even if I click on it.
Here is my code:
// Use this for initialization
void Start ()
{
UnitPortrait1 = UnitPortrait1_Object.GetComponent<UnityEngine.UI.Image> ();
UnitPortrait2 = UnitPortrait2_Object.GetComponent<UnityEngine.UI.Image> ();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKey (KeyCode.LeftControl)) {
if (Input.GetKeyDown (KeyCode.Mouse0)) {
print ("test0");
if (UnitPortrait1.Raycast (Input.mousePosition, camera1)) {
print ("Image1 clicked");
Unit1Selected = true;
Unit2Selected = false;
}
if (UnitPortrait2.Raycast (Input.mousePosition, camera1)) {
print ("Image2 clicked");
Unit1Selected = false;
Unit2Selected = true;
}
}
}
}
If you know what is wrong, or if there is a more efficient way to do what I want, please tell me.
Answer by Bunny83 · Jan 28, 2017 at 01:38 PM
Graphic.Raycast can't be used to manually cast a ray against the graphic. It's just an internally used method to "filter out" invalid raycast positions. Make sure you read my comment as well ^^. I probably should include that in my answer over there.
Answer by PizzaPie · Jan 27, 2017 at 07:42 PM
Why bother with raycast on UI elements when you can use events. Add the event OnClick() on each image on the editor and assign the functions you want to run OnClick (the easy way) or make use of the IPointerClickHandler or IPointerSelectHandler (a bit more advanced).
Ok, so I have figuered out that there was a much simpler way to do what I want.
I use buttons ins$$anonymous$$d of images and as @PizzaPie said, I used OnClick() to call the function I want on an other object in the scene. This object has one script with all the function I want to use, so it is much easier to use as all variables are in the script.
How the hell my comment became an answer??? :D anyway to the point, you don't have to use a button as you can attach the a component: event-> OnClick to any UI element in case you don't want the fancy staff that comes with a button it is better to use an image as it requires much less memory. In great scales for a Pc it might have no difference but for a mobile it will.
Answer by FortisVenaliter · Jan 27, 2017 at 08:19 PM
Well, the mouse is not a key, so I doubt GetKeyDown would ever trigger for it. Why not use GetMouseButtonDown instead?
I tested and the get$$anonymous$$eyDown works. the problem is the raycast.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Raycast from camera not hitting Terrain 1 Answer
Raycast pink material 1 Answer
How to find all colliders below mouse? 2 Answers