- Home /
The question is answered, right answer was accepted
Operator || cannot be applied to types float and float?
Hi I keep getting an error with my code while following a tutorial on making rigidbody character controllers. Operator '||' cannot be applied to operants of type 'float' and 'float'. Im following the tutorial from the book unity 3.x scripting/cookbook. Except instead of using java, its in C#.
the java version from the tutorial:
public var Speed : float = 5.0;
public var MoveDirection : Vector3 = Vector3.zero;
function Movement (){
if (Input.GetAxis("Horizontal") || Input.GetAxis("Vertical"))
MoveDirection = Vector3(Input.GetAxisRaw("Horizontal"),MoveDirecti
on.y, Input.GetAxisRaw("Vertical"));
this.transform.Translate(MoveDirection);
My version
public float speed = 5.0f;
public Vector3 moveDirection = Vector3.zero;
private float h = Input.GetAxis("Horizontal");
private float v = Input.GetAxis("Vertical");
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void Movement()
{
if( Input.GetAxis("Horizontal") || Input.GetAxis ("Vertical") )
moveDirection = Vector3( h, moveDirection.y, v);
this.transform.Translate(moveDirection);
}
Answer by VesuvianPrime · Sep 13, 2014 at 12:37 PM
I'm not familiar with Java, but in Python you can use most (all?) objects as booleans, which I presume is what the book is trying to do.
For example, the following is legal in Python:
if 0.0: # Evaluates to False
DoSomething()
elif 26.1: # Evaluates to True (the float isn't zero)
DoSomethingElse()
But the following is illegal in C#:
if (0.0f)
DoSomething();
else if (26.1f)
DoSomethngElse();
C# doesn't let you cast things to booleans like that.
So, reading your code, I presume the author was simply trying to detect if there is any motion on either of the input axis.
The check you probably want to be making is:
bool horizontal = !Mathf.Approximately(Input.GetAxis("Horizontal"), 0.0f);
bool vertical = !Mathf.Approximately(Input.GetAxis("Vertical"), 0.0f);
if (horizontal || vertical)
...
I see now. Thank you Very much. Its C# that doesnt let that happen. I switched it over to Java like it was intended and it seems to be working fine. I was hoping to be able to initialize GetAxis into a variable though, but JavaScript doesnt let that happen apparently. At least without any errors, but this will do. Thank you.
Follow this Question
Related Questions
error CS0019: Operator `&' cannot be applied to operands of type `float' and `float' 0 Answers
the type or namespace cannot be found 0 Answers
Operator cannot be used with left hand side of type.... 1 Answer
How to compare float for equality? 2 Answers
Illumination-based Stealth System using built-in dynamic shadows? 0 Answers