The question is answered, right answer was accepted
Can't use Raycast to detect if I look at object
I have tv with 3 buttons and 3 screens. Each button disable all screens and then enable it's own screen. Button is empty GP with the box collider only. I want to use a Raycast to detect when I look at Button1, Button2 or Button3. And after pressing LMB I want to enable one of 3 screens. But my code doesn't work...
public GameObject screen1;
public GameObject screen2;
public GameObject screen3;
private Collider thisCollider;
private int channelNumber;
void Start ()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButton("Fire1"))
if (DoPlayerLookAtButton())
ChangeChannel();
}
bool DoPlayerLookAtButton()
{
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 1.5f);
if (isHit && _hit.collider == thisCollider) // with the second condition it doesn't work
{
switch (thisCollider.name)
{
case "Button1": channelNumber = 1; break;
case "Button2": channelNumber = 2; break;
case "Button3": channelNumber = 3; break;
default: break;
}
return true;
}
else
return false;
}
void ChangeChannel()
{
DisableAllScreens();
switch (channelNumber)
{
case 1: screen1.SetActive(true); break;
case 2: screen2.SetActive(true); break;
case 3: screen3.SetActive(true); break;
default: break;
}
}
void DisableAllScreens()
{
screen1.SetActive(false);
screen2.SetActive(false);
screen3.SetActive(false);
}
So the script works, but if you include:
&& _hit.collider == thisCollider
The code inside condition stops executing, is that correct?
If so why don't you check what is the raycast hitting? If it's not thisCollider, then it shoud be something else, or if it hits something at all...
Is this script attached to the object, that have to be hit by the raycast?
Without && _hit.collider == thisCollider
I can press on any collider on the scene and it will work. But I want it to work only when I press the button. Yes, script attached to the object, that have to be hit by the raycast - empty GO with collider
ok. Then the Raycast is hitting something.
Have you tried to Debug the hit.collider.name, to see what does it hit?