Why aren't I picking up the first object every time, with a Raycast ?

I have never come across this before, and there are probably alternative ways to deal with this, but here goes -

I have a SpaceShip, over a platform (A modified Cube Primitive). I am using the “Water” from the Standard Assets, so underneath that there is a plane to “hit”, when the platform is not below. Thus I want to detect whether it is a Platform, or over the “seabed” (Tagged as “Base” in code") -

void Update () {
if (OverPlatform())
isAbovePlatform = true;
else
isAbovePlatform = false;
}

bool OverPlatform()
{
RaycastHit hit;
bool abovePlatform = false;
if (Physics.Raycast(transform.position, -Vector3.up, out hit))
{
if (hit.transform.gameObject.tag.Equals(“Platform”))
{
Debug.Log(“Platform hit”);
abovePlatform = true;
}
else
{
Debug.Log(“base hit”);
abovePlatform = false;
}
}
return abovePlatform;
}

My problem is that when the ship is above the platform, on each iteration of Update(), it is alternating between the platform and the base, surely the platform, as the first object underneath, would be found first every time ?

Please use code tags Using code tags properly - Unity Engine - Unity Discussions

Yes you are right that it should hit the platform every time, I don’t see any reason it wouldn’t do that with the code you posted. Maybe you can show some screenshots / video?

My apologies, I was originally going to post this in “Answers”, and did a straight C&P…

Here’s a screen shot from the Editor, and a little of the Console output. “Base” is of course out of view, below the water.

2883107--211728--Untitled.png

I don’t see any reason why this would happen, maybe try to debug the raycast with Debug.DrawRay

1 Like

Ah okay, thanks for that. A “facepalm” moment I’m afraid, I feel a little silly… the reason why was that there were two rays - I had attached the same Detector script to a camera in the scene, for no real reason either, not that I recall… oh well…

1 Like