Why is this not working?
I'm trying to detect the position of the player, and if the position is equal to a certain value, the player will teleport (to the next level). This is my code:
public class Portal : MonoBehaviour {
public float num1 = -4.896353;
public float num2 = 1.298981;
public float num3 = -17.98553;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(gameObject.transform.position==new Vector3(num1, num2, num3)){
Application.LoadLevel(1);
}
}
}
(My copying and pasting is bad - all the syntax/indentation is correct)
The error I receive when trying to run this code is that I cannot convert to double to float. Please help!
Answer by Jessespike · Nov 15, 2015 at 11:53 AM
float values need to be followed by f or F
public float num1 = -4.896353F; // <- Notice the "F"
public float num2 = 1.298981F;
public float num3 = -17.98553F;
Without the f/F, the compiler will treat numeric values as doubles. Doubles are like floats, but are 2x larger and more precise.
Answer by DiegoSLTS · Nov 15, 2015 at 02:35 PM
You should never compare float values with a == operand, it's a really common issue and the compiler might be warning you about it if you read the console. Your code compares Vector3s, which in the end compares 3 floats value with other 3 float values.
You should compare if the values are close enough for what you want to do. Something like:
if(Vector3.Distance(transform.position,new Vector3(num1, num2, num3)) < 0.1f) { //0.1 is just an example
Application.LoadLevel(1);
}
For more info on why this happens, read this: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm