Skip to content

Use Key

Henry de Jongh edited this page Mar 10, 2023 · 3 revisions

There are many games that allow the player to use an object, often with the E-Key.

Here is an example component of how you could implement such a feature into your game. You can attach this component to the camera and press the E-Key to invoke the "Use" input on any reactive logic component that has a collider.

public class PlayerUse : MonoBehaviour, IReactive
{
    [Required IReactive Implementation] // the closed region.

    private static ReactiveMetadata _reactiveMeta = new ReactiveMetadata();

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (Physics.Raycast(new Ray(transform.position, transform.forward), out var hit, 1f, ~0, QueryTriggerInteraction.Collide))
            {
                var reactive = hit.collider.gameObject.GetComponent<IReactive>();
                if (reactive != null)
                {
                    ReactiveLogicManager.Instance.ScheduleInput(new ReactiveObject(gameObject), this, reactive, "Use", 0.0f, "");
                }
            }
        }
    }

    public void OnReactiveInput(ReactiveInput input)
    {
    }
}

We manually call ReactiveLogicManager.Instance.ScheduleInput because we have a specific IReactive instance that should receive the "Use" input (and not outputs on this component).

By adding colliders to these buttons it's now possible to press the E-Key and invoke the "Use" input which presses them:

Showcasing Dynamic Lighting and Reactive Logic by switching some light sources

Clone this wiki locally