if (Physics.Raycast(CameraPlayer.transform.position, CameraPlayer.transform.forward, out hit, Range, LayerMask.GetMask("ActiveItem")))
{
Debug.Log("If");
}
else
{
Debug.Log("Else if");
}
And my problem is that it both detects the collision and not at the same time. So “Debug Log” prints both “If” and “Else if”. This causes the code to do things for both of these cases. I don’t know what’s wrong, I checked everything I could. Does anyone know where I am making a mistake?
It sounds like the issue might be with the layers or the layer mask that you are using in the Raycast method. The Raycast method will only detect collisions with objects that are on the specified layers, and the LayerMask parameter allows you to specify which layers to check.
In your code, you are using the LayerMask.GetMask() method to get a layer mask for the “ActiveItem” layer. However, it looks like the Raycast is detecting collisions with objects on other layers as well. This is why the Debug.Log statement in the “else” block is being called.
To fix this issue, you will need to ensure that only objects on the “ActiveItem” layer are being detected by the Raycast. You can do this by using the Physics.Raycast() overload that takes a layerMask parameter, and passing in the layer mask for the “ActiveItem” layer. This will ensure that only objects on that layer are detected by the Raycast, and the “else” block will only be executed if the Raycast does not hit any objects on that layer.
Here is an example of how you could modify your code to do this:
// get the layer mask for the "ActiveItem" layer
int layerMask = 1 << LayerMask.NameToLayer("ActiveItem");
// use the layer mask in the Raycast method
if (Physics.Raycast(CameraPlayer.transform.position, CameraPlayer.transform.forward, out hit, Range, layerMask))
{
Debug.Log("If");
}
else
{
Debug.Log("Else if");
}
I hope this helps! Let me know if you have any other questions.