I have a machine and a I want to check if I can place a conveyor at its connexion point. I do it by checking if the machine is at the expected Input position of the conveyor and if the conveyor is at the expected output position of the machine. Here is the code:

void AddFirstPart(List<Vector3> pValidInPositions, List<Vector3> pValidOutPositions)
        pValidInPositions.ForEach(o => Debug.Log(o));

        if (-StartObject.transform.up + StartObject.transform.position == ghostTransform.position && pValidInPositions.Contains(StartObject.transform.position))
            CreatePart(Mathf.RoundToInt(ghostTransform.rotation.eulerAngles.z), null, transform.gameObject);

The reason why the input position of the conveyor is in a list is because I can also place conveyors with 3 connexions, so I just use the list for both to make it more simple.

When the StartObject (the machine) isn't rotated (facing down) it works most of the time and when its not, it doesn't work most of the time, and it's somewhat random. In the console, when it works and when it SHOULD work, the same values are written for the position of StartObject and the position of the Conveyor Input. However, when it doesn't work, the pValidInPositions.Contains(StartObject.transform.position) returns false.

Why isn't it always returnign true when it should ?

not working


  • \$\begingroup\$ I'm not familiar enough with Unity to say definitively that this is the source of your problem, but in general, testing floats for strict equality (as represented by your == test on positions) is error prone. \$\endgroup\$ – Pikalek Jun 4 at 18:03
  • 1
    \$\begingroup\$ Try outputting your vectors to round-trip precision (eg. myVector.x.ToString("R") ) - that will help you see if they're actually the same, or just rounding for display. As Pikalek says, comparing float values for exact equality is a terrible idea. It's even worse in the way you've done it here, where you're using both the == operator (which for vectors returns true if they're within 1/100 000 th of a unit of each other), and .Contains which uses .Equals, which returns true only if the vectors are absolutely identical. So the two tests don't match. \$\endgroup\$ – DMGregory Jun 4 at 18:05
  • \$\begingroup\$ Would the solution be to compare them after using Mathf.RoundToInt() ? \$\endgroup\$ – Samuel Fyckes Jun 4 at 18:27
  • 1
    \$\begingroup\$ Do you care only about integer coordinates? If so, you might want to use integers throughout. \$\endgroup\$ – DMGregory Jun 4 at 18:46
  • \$\begingroup\$ Yea I only want integer values... So I can I can round the x,y and z when creating my vector ? \$\endgroup\$ – Samuel Fyckes Jun 5 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.