I want to make a script so that the player can control some levers or buttons within some range (example 5 meters),and when he press button or pull a lever some action happens.
I do not have idea how to do that,maybe with raycast but i still do not have whole idea how to do that. If there is some better way could you please tell me
A simple simple way is to make an empty GameObject and add a BoxCollider to it and set Is Trigger to true. From there add a class to that GameObject with something like:
public class Trigger : MonoBehaviour
{
[SerializeField] private bool triggerActive = false;
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
triggerActive = true;
}
}
public void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
triggerActive = false;
}
}
private void Update()
{
if (triggerActive && Input.GetKeyDown(KeyCode.Space))
{
SomeCoolAction();
}
}
public void SomeCoolAction()
{
}
}
Please note: This assumes your player has the tag “Player”, which is a default tag in the tag list. Also it means your player needs to have some kind of collider as well (BoxCollider, SphereCollider, MeshCollider, something like that).
There’s other ways, but there’s a quick intro option.
You have OnTriggerEnter and OnTriggerExit. When the player’s collider start touching the trigger he is able to press the Space bar to use that ‘SomeCoolAction’ method. When he stops touching that collider he won’t be able to call SomeCallAction. So set the size of that collider to the area you want the player to be able to interact with the button. Only when triggerActive is active will the player be able to interact with it.
Ok thanks i know how to do it but that way does not suit my needs.Because i want that player can interact with object only when its facing the object (like little cross on the center of the screen and when i align that cross to object then i can interact).From this with trigger i could just enter the trigger and press key.Probably raycast is what i need but i do not know how to implement all that to function with raycast