I want to interact with gameobjects in Unity. These objects might be keys, doors, chests, ...
Let's say there is a key on a table. When the player comes closer it should get outlined by a shader and a text appears "pick up key".
I created an interface for interactable gameobjects.
public interface IInteractable
{
string InteractabilityInfo { get; }
void ShowInteractability();
void Interact();
}
By doing this I can add the interface component to my Key script
public class Key : MonoBehaviour, IInteractable
{
public string InteractabilityInfo { get { return "some text here"; } }
public void ShowInteractability()
{
// Outline Shader maybe?
}
public void Interact()
{
// Do something with the key
}
}
When it comes to a script that checks if something is interactable I created a script that creates a raycast which checks for interactables. (I attach this script to my FPS camera)
public class InteractabilityCheck : MonoBehaviour
{
private const int RANGE = 3;
private void Update()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, RANGE))
{
IInteractable interactable = hit.collider.GetComponent<IInteractable>();
if (interactable != null)
{
interactable.ShowInteractability();
if (Input.GetKeyDown(KeyCode.E))
{
interactable.Interact();
}
}
}
}
}
This script tries to get the interface component and calls the methods from it if it's not null.
This code works fine but what I don't like is that the Raycast fires one per frame. Is there another way achieving interactability?