When I look at some object and press the button, I need to do something. When I do it for the first time, it works, but then I don’t need to press the button again, I can just look at object. But player must look at object and press the button, not only look
private Collider thisCollider;
public int ActionNumber { get; private set; }
void Start ()
{
thisCollider = GetComponent<Collider>();
}
void Update ()
{
if (Input.GetButton("Fire1") && DoPlayerLookAtObject())
ActionsList();
}
bool DoPlayerLookAtObject()
{
// Ignoring player's collider
int layerMask = 1 << 9;
layerMask = ~layerMask;
RaycastHit _hit;
Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
bool isHit = Physics.Raycast(_ray, out _hit, 2.0f, layerMask);
if (isHit && _hit.collider == thisCollider)
return true; // this return true all the time after first interaction with object
else
return false;
}
public bool ActionsList()
{
if (DoPlayerLookAtObject())
switch (thisCollider.name)
{
case "barthender": ActionNumber = 1; return true;
case "doorToStreet": ActionNumber = 2; return true;
default: Debug.Log("Error: Out of range"); break;
}
return false;
}
How I use it:
public OnMousePressCasino onMousePressCasinoBarthender;
public OnMousePressCasino onMousePressCasinoDoorToStreet;
if (onMousePressCasinoBarthender.ActionNumber == 1 &&
onMousePressCasinoBarthender.ActionsList())
// do something
if (onMousePressCasinoDoorToStreet.ActionNumber == 2 &&
onMousePressCasinoDoorToStreet.ActionsList())
// do something
Ignoring player’s collider: