Question by
r3flx · Apr 29, 2020 at 01:07 PM ·
raycastgetcomponentdetection
Is there a better way to check if a player is looking at a certain object?
Right now, I have a script to raycast at an object and check if it contains a script via GetComponent<>:
RaycastHit hit;
if (Physics.Raycast(cameraController.transform.position, cameraController.transform.forward, out hit, useRange))
{
Debug.DrawLine(cameraController.transform.position, hit.point, Color.red);
if (hit.transform.GetComponent<FarmlandController>())
{
FarmlandController fc = hit.transform.GetComponent<FarmlandController>();
promptText.text = "Press E to harvest " + fc.farmland.plant.name;
isLookingAtObject = true;
}
else
{
isLookingAtObject = false;
}
}
else
{
isLookingAtObject = false;
}
I want to know if there is a better way to do this? If I have multiple object that I want to interact with but they are under different monobehaviour scripts i would have to do a switch case etc. Sounds messy. Any tips? Thanks.
Edit: Would interfaces be a viable option? If i create a IUsable interface and check for the interface instead?
Comment