I need explanation.

I’m working on a small mobile game. In it I used a raycast to be able to tell when player clicks on a certain object. Suddenly I noticed a weird behavior when one object was covering another. It sometimes returned the the object behind instead of the one in the front. After some testing I learned that RaycastHit was returning a wrong hit position. This is where I got stuck I started debugging for hours(I even went to the second page on google reading all the threads with similar issues) I was about to give up, but then I commented a bit of code that modified the position of objects. It suddenly started working.

This is the code that made raycast stop working it was called in every FixedUpdate:

Vector2 position = gameobject.transform.position;
position.x = 0.5f*targetx+ 0.5f*position.x;
gameobject.transform.position = position;

I started trying different things to fix it and changing the above code to this one below made it work again:

gameobject.transform.position = new Vector3(targetx * 0.5f + 0.5f * gameobject.transform.position.x, gameobject.transform.position.y, gameobject.transform.position.z);

Can someone explain me WHY changing the code above to the one below fixed it? I’m pretty sure that they both do exactly the same thing.

I found the answer. By mistake I wrote Vector2 instead of Vector3. Why assigning a Vector3 to Vector2 didn’t give me an error is beyond me. It really shouldn’t convert implicitly like this. It creates hard to find bugs. I guess you learn something new everyday.

Well, one difference that I notice:

transform.position is a Vector3. In your first code example, the local variable “position” is a Vector2. In the last line, it is automatically “promoted” to a Vector3 so it can be assigned to transform.position, which means it gets a default Z value of zero.

In your second code example, you keep the same Z value that you already had.