Only one raycast out of two works as intended

Hi!

First of all, the name for this problem was hard to come up with. Second of all, here’s the problem.

So I have this RTS colony style game and I want to be able to build corridors and I want the doorways to connect to other doorways. But here’s my problem. I have 2 doorways on a simple corridor. Only one works to detect a doorway that the corridor can be attached too. If I rotate it, it detects the other doorway from the other corridor I want to connect with.

Here’s my code for this detection:

Doorway[] doorways = cursor.GetComponentsInChildren<Doorway>();

            Debug.Log(doorways.Length);

            foreach (Doorway door in doorways)
            {
                if (Physics.Raycast(door.transform.position, door.transform.forward, out doorHit, 1.1f, doorLayer))
                {
                    Debug.Log("Can place room");
                    Debug.DrawRay(door.transform.position, door.transform.forward, Color.green);
                    canPlaceRoom = true;
                }
                else
                {
                    Debug.Log("Can't place room");
                    Debug.DrawRay(door.transform.position, door.transform.forward, Color.red);
                    canPlaceRoom = false;
                }
            }

            Debug.Log(canPlaceRoom);

I know what the problem is (it is that it uses the first doorway it can find in the array) or at least I think I know but I do not know how I can solve it.

Thanks in advance.

if it works ok with second door when you rotate, then you have to use 2 raycasts, one is yours and second with -door.transform.forward that will flip the direction of ray.

You are setting the direction of the ray relative to the doorway’s transform, so when you rotate it, so does the ray. If you are looking for absolute forward direction, then use Vector3.forward instead. Other than that, the code is fine. The issue is in your logic. So more context would be helpful.