- Home /
Question by
SheepState · Jun 27, 2014 at 01:42 AM ·
floatboolconvertingto
Converting Float to Bool
When I try to do this script it doesn't work but in my mind it seems that it should work it tells me that it cant convert a float into a bool. Please help. This is my script
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public bool isWalking = false;
public float playerSpeed = 5.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetAxis("Horizontal") == true) {
transform.Translate (Vector3.right * Input.GetAxis ("Horizontal") * playerSpeed * Time.deltaTime);
isWalking = true;
}
else {
isWalking = false;
}
}
}
Comment
Answer by danielmahon · Aug 07, 2020 at 03:13 PM
Recently needed to handle this with the new Input System. To solve I added an extension method to "float" that will return the float as a bool.
// Extension method
public static bool AsBool(this float value) {
return Mathf.Approximately(Mathf.Min(value, 1), 1);
}
// Usage example (holding shift key)
bool _modifySelection = _pointerSelectModifier.action.ReadValue<float>().AsBool();
// will return "true" if button is currently pressed, the value is >= 1