The question is answered, right answer was accepted
C# Boolean Stuck as False
I have a bool in my script that is stuck as false. I tried changing if(clickCheck) to if(clickCheck == true) but it's still stuck as false. I believe this is due to the if statement being bypassed somehow. I have clickCheck set to false in the inspector so I don't know why it's being bypassed.
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using UnityEngine.UI;
using System.Collections;
public class KeyPressString : MonoBehaviour, IPointerClickHandler {
public Text text;
public bool clickCheck;
public PressedStringEvent OnPress;
void Update(){
if(clickCheck == true){
if(Input.inputString != null){
OnPress.Invoke(text.text);
clickCheck = false;
}
}
}
public void OnPointerClick(PointerEventData eventData){
clickCheck = true;
}
}
[System.Serializable]
public class PressedStringEvent : UnityEvent<string>{}
Ok, I found out from the Debug.Log that clickcheck becomes true for a millisecond and goes back to false. If I remove clickcheck = false then the bool isn't stuck. So clickcheck is stuck as being assigned. This might be due to how the functions run but I'm not sure.
yes your routine is
if (bool)
{
bool = !bool;
}
if you expected something else to happen between but it doesnt it means that Input.inputString == null, surely?
This is a good example of a 'OneShot' routine. It fires once then switches itself off so it doesnt run again until told to. On->DoStuff->Off
Answer by Bunny83 · Nov 03, 2015 at 01:14 AM
As far as i know "Input.inputString" is never "null". It's most likely an empty string.
In general it's safer to use string.IsNullOrEmpty
if(clickCheck){
if(!string.IsNullOrEmpty(Input.inputString)){
OnPress.Invoke(text.text);
clickCheck = false;
}
}