- Home /
How to use Input.GetAxis in if statement
Hey guys, i'm struggeling with Input.GetAxis right now. I would like to jump when pressing a button on my PS4 controller. I always get the error
error CS0019: Operator '&&' cannot be applied to operands of type 'float' and 'bool' GetAxis is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'PlayerController'.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public int speed = 5;
public int turnSpeed = 100;
public Rigidbody rb;
public bool jumpingAllowance;
public GameObject playerGun;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Input.GetAxis("Horizontal") * speed * Vector3.right * Time.deltaTime);
transform.Translate(Input.GetAxis("Vertical") * speed * Vector3.forward * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.R) && Input.GetKeyDown(KeyCode.W))
{
speed = 10;
}
else
{
speed = 5;
}
}
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.Space) && jumpingAllowance)
{
jumpingAllowance = false;
rb.AddForce(Vector3.up * 7, ForceMode.Impulse);
}
if(Input.GetAxis("Jump") && jumpingAllowance)
{
jumpingAllowance = false;
rb.AddForce(Vector3.up * 7, ForceMode.Impulse);
}
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Ground"))
{
jumpingAllowance = true;
}
else
{
jumpingAllowance = false;
}
}
}
Answer by KittenSnipes · Feb 01, 2020 at 11:37 PM
@niedery572
I will only be describing the errors that you have posted to help guide you to the answer. First off get axis is a float that you have neglected to compare to another float in your if statement so of course that statement won’t work. So if you really want to use the GetAxis(“Jump”) in your If statement then think about what getaxis does and what happens inside the if statement. Remember you must have only Bools inside if statements. So by comparing a float to a float you create such circumstances. Sorry for ranting lol hopefully you can get the answer now.
Your answer
![](https://koobas.hobune.stream/wayback/20220612222545im_/https://answers.unity.com/themes/thub/images/avi.jpg)