- Home /
Image does not display correctly after fulfilling the conditions
The intent of the following code is to display the validationOk image when the condition is met. If not the validationNotOk image should be displayed and validationOk should disappear. At the moment the validationNotOk image displays correctly but when the condition is met the validationOk image flashes alternately with the validationNotOk image. Could you please suggest what is incorrect here (value angle is changing continuously)?
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class TouchPosition : MonoBehaviour
{
public bool isValid;
public Image validationOk, validationNotOk;
private void Start()
{
validationOk.enabled = false;
validationNotOk.enabled = false;
isValid = false;
}
void Update()
{
VerifyAngle(angle);
}
private void VerifyAngle(float angle)
{
if(angle > 90 && angle < 91 && Input.touchCount > 2 && isValid == false)
{
validationNotOk.enabled = false;
validationOk.enabled = true;
isValid = true;
}
else if(Input.touchCount > 2)
{
validationOk.enabled = false;
validationNotOk.enabled = true;
isValid = false;
}
}
}
Answer by bacon_nugget · Apr 03 at 12:15 PM
When isValid
is set to true, it makes the first if statement always evaluate false. If there are still more than two touches active at that point, then that means the code will instead move into the contents of the second if statement where it switches back to not valid. That's why you're seeing the flickering. Since you only ever have one image or the other, I think you can simplify this code a ton by applying the boolean expression directly to the enabled
property of the images.
var valid = angle > 90 && angle < 91;
var showImage = Input.touchCount > 2;
validationOk.enabled = showImage && valid;
validationNotOk.enabled = showImage && !valid;
It works perfectly, thank you very much - I actually missed it somewhere. I have one more question: this if statement is based on touching the screen with my fingers - do you know how to make the image disappear when I no longer touch the screen? When I touch it with three fingers, the relevant image is shown but remains on the screen when I take my fingers off the screen, I would like nothing to be visible when there are no fingers on the screen.
@matrix1395 Huh, that's strange. When there are no touches on the screen, that means var showImage = Input.touchCount > 2;
should give showImage = false
which would disable both images. Try throwing in some Debug.Logs and check if Input.touchCount is changing properly when you take your fingers off the screen
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
help for the background image 0 Answers
IF Statement Being Ignored 3 Answers
Change size of an object up to a limit 2 Answers