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);
		

	}

1 Answer

1

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.