- Home /
Can't convert int to bool?
I'm not trying to convert an int to a bool. I am scripting in c sharp and when I come to this line it throws out this error!
r.drag = body.grounded ? 1 : 0.1f;
Why does this error pop up? r is the name that I gave to the rigidbody of body, grounded is a bool that shoes whether or not the player is touching the ground. Thanks for any help!
body.grounded is probably an int.
You need to start a trinary operator with a boolean expression.
What are you actually trying to accomplish with that line of code?
If thats not it, then it is likely that r.drag is a boolean, but i suspect the former.
Here's the full script if you could give me a write out solution.
using UnityEngine;
using System.Collections;
public class GravityAttractor : $$anonymous$$onoBehaviour
{
//SET TO TRUE FOR $$anonymous$$ONO-DIRECTIONAL GRAVITY
private bool useLocalUpVector = false;
//FORCE APPLIED ALONG GRAVITY UP VECTOR(NEGATIVE = DOWN)
public float gravityForce = -10;
public void Attract(PlanetaryGravity body)
{
Vector3 gravityUp;
Vector3 localUp;
Vector3 localForward;
Transform t = body.transform;
Rigidbody r = body.rigidbody;
//FIGURE OUT THE BODIES UP VECTOR
if(useLocalUpVector)
{
gravityUp = transform.up;
}
else
{
gravityUp = t.position - transform.position;
gravityUp.Normalize();
}
// Accelerate the body along its up vector
r.AddForce( gravityUp * gravityForce * r.mass );
r.drag = body.grounded ? 1 : 0.1f;
// If the object's freezerotation is set, we force the object upright
if(r.freezeRotation)
{
// Orient relatived to gravity
localUp = t.up;
var q = Quaternion.FromToRotation(localUp, gravityUp);
q = q * t.rotation;
t.rotation = Quaternion.Slerp(t.rotation, q, 0.1f);
localForward = t.forward;
}
}
}
What's the exact text of the compile error?
You may be able to fix this by changing 1
to 1f
. The two outputs of a ternary operator must have a common type; you're offering an int and a float, and I don't know offhand if the compiler will cast implicitly.
t might be a problem with my conversion from Javascript to C Sharp?
Answer by Bunny83 · May 21, 2014 at 02:28 AM
Since your "grounded" variable is an int you have to convert it to a boolean state "is grounded". From your code it seems that you're grounded when the "grounded" integer is greater than 0, so just use the greater-than operator like this:
r.drag = (body.grounded > 0) ? 1f : 0.1f;
Alternatively you could also add this property to your PlanetaryGravity class:
public bool IsGrounded
{
get {return grounded > 0;}
}
and use the property instead:
r.drag = body.IsGrounded ? 1f : 0.1f;
Answer by zsolti · Jan 06, 2015 at 02:26 PM
bool abc=(x == 1); if (x==1) //abc=true else //abc=false