Newer
Older
Hierarchical-Task-Network-Unity-3D / Assets / Scripts / MouseInteractor.cs
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

public class MouseInteractor : MonoBehaviour
{
    [Header("Input")]
    [SerializeField] private InputActionAsset inputActions;
    private InputActionMap actionMap;
   
    private InputAction interactInputAction;

    private Camera cam;

    private IOutliner highlighetedObject;

    private void Awake()
    {
        actionMap = inputActions.FindActionMap("Player");
        cam = GetComponent<Camera>();
        interactInputAction = actionMap.FindAction("Interact");
    }

    private void OnEnable()
    {
        actionMap?.Enable();
        interactInputAction.performed += OnInteractPerformed;
    }

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnInteractPerformed(InputAction.CallbackContext ctx)
    {
        Ray ray = cam.ScreenPointToRay(Mouse.current.position.ReadValue());

        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            if (hit.collider.TryGetComponent(out IOutliner outliner))
            {
                if (highlighetedObject != null)
                {
                    highlighetedObject.ToggleOutline(false);
                }

                highlighetedObject = outliner;
                outliner.ToggleOutline(true);

            }
            else
            {
                if (highlighetedObject != null)
                {

                    highlighetedObject.ToggleOutline(false);
                    highlighetedObject = null;
                }
                Debug.Log("Hit something, but it has no outliner.");
            }
        }
    }

    private void OnDisable()
    {
        actionMap?.Disable();
        interactInputAction.performed -= OnInteractPerformed;
    }
}