Home > other >  cannot convert double into float
cannot convert double into float

Time:10-18

This is where the error is.

Vector3 targetPosition = new Vector3(target.position.x, target.position.y 1.29, transform.position.z);

In target.position.y 1.29

it's the 1.29

If it's just int it is ok but I want to be precise.

public Transform target;
public float smoothTime = 0.2f;
private Vector3 _velocity = Vector3.zero;

void LateUpdate()
{
    Vector3 targetPosition = new Vector3(
        target.position.x, target.position.y   1.29
        , transform.position.z);
    transform.position = Vector3.SmoothDamp(transform.position,
        targetPosition, ref _velocity, smoothTime);
}

}

CodePudding user response:

The following statement should work just fine, with the f after the floating-point number.

Vector3 targetPosition = new Vector3(
    target.position.x, target.position.y   1.29f
    ,transform.position.z);

Now, why do we need to specifically have to denote f for floating-point and not for another data type, when in other languages it's default?

So, the answer is that in C# any floating-point number without any notation is considered as double by default. and in Unity, most of the Mathematics is being calculated in float my reasoning for this is that float has less accuracy in floating-point calculation compare to double, and due to this less accuracy the processing power needed to calculate is less the doubles so I guess due to this Unity might have chosen float instead of double, but this is just my speculation/reasoning using my current knowledge.

TL;DR

We should use f notation to denote floating-point numbers when dealing with Unity's Mathematics, ie. Vectors, Regidbodies, Quaternions, etc. Otherwise, C# and unity will both consider this as double and will throw an error type miss-match.

CodePudding user response:

The following code below should work.

Vector3 targetPosition = new Vector3(target.position.x, target.position.y   (float)1.29, transform.position.z);

You can convert a double to float using (float).

Explanation:

You are getting the error because 1.29, by itself, is a double. When creating a new Vector3, you need 3 floats.

  • Related