- Home /
Why Can't I Use the '^' Operator? Error CS0019
I have a simple function that calculates the distance between 2 GameObjects using the following formula:
I get the following error: Assets\Sight.cs(151,27): error CS0019: Operator '^' cannot be applied to operands of type 'float' and 'float'
and I don't know why.
here is my simple function code and thank you in advance!
public float distance(Vector3 a, Vector3 b)
{
return Mathf.Sqrt((a.x - b.x)^2 + (a.z - b.z)^2);
}
Answer by finnjwohner · Jul 13, 2020 at 11:11 PM
Use Mathf.Pow(float a, float b) instead.
Yeah exactly that, also, Unity has a built in function to do what you're trying to achieve, Vector3.Distance(Vector3 a, Vector3 b) that returns a float just in case you're not aware of that.
Answer by Bunny83 · Jul 13, 2020 at 11:30 PM
In C# the ^ operator is the bitwise xor operator and does not calculate the power. Like finnjwohner said to calculate an arbitrary power you would use Mathf.Pow.
However in this case it would be unnecessary overhead. First of all Unity already has a method to calculate the distance between two points: Vector3.Distance so writing your own is unnecessary. In your case it seems you are only interested in the x-z plane distance. So the easiest solution would be to cancel the y difference and use Vector3.Distance or do something like this:
public static float Distance(Vector3 a, Vector3 b)
{
a.y = b.y = 0f;
return Vector3.Distance(a, b);
}
// or this
public static float Distance(Vector3 a, Vector3 b)
{
Vector3 d = a - b;
return Mathf.Sqrt(d.x*d.x + d.z*d.z);
}