Answers for "use raycast unity new input system"

C#
0

use raycast unity new input system

With this code somewhere in your scene:

using UnityEngine.InputSystem;
using UnityEngine;

public class MouseClicks : MonoBehaviour
{
    [SerializeField]
    private Camera gameCamera; 
    private InputAction click;

    void Awake() 
    {
        click = new InputAction(binding: "<Mouse>/leftButton");
        click.performed += ctx => {
            RaycastHit hit; 
            Vector3 coor = Mouse.current.position.ReadValue();
            if (Physics.Raycast(gameCamera.ScreenPointToRay(coor), out hit)) 
            {
                hit.collider.GetComponent<IClickable>()?.OnClick();
            }
        };
        click.Enable();
    }
}
You can add an IClickable Interface to all GameObjects that want to respond to clicks:

public interface IClickable
{
    void OnClick();
}
and

using UnityEngine;

public class ClickableObject : MonoBehaviour, IClickable
{
    public void OnClick() 
    {
        Debug.Log("somebody clicked me");
    }
}
Posted by: Guest on August-24-2021

Code answers related to "use raycast unity new input system"

C# Answers by Framework

Browse Popular Code Answers by Language