Certainly! Here's an example of a C# MonoBehaviour class that takes in the mouse position and click input using the new Input System in Unity:
using UnityEngine;
using UnityEngine.InputSystem;
public class MouseInputHandler : MonoBehaviour
{
private Vector2 mousePosition;
private bool isMouseClicked;
private void OnEnable()
{
// Enable the mouse input action
Mouse.current.position.performed += OnMousePositionPerformed;
Mouse.current.leftButton.performed += OnMouseClickPerformed;
}
private void OnDisable()
{
// Disable the mouse input action
Mouse.current.position.performed -= OnMousePositionPerformed;
Mouse.current.leftButton.performed -= OnMouseClickPerformed;
}
private void OnMousePositionPerformed(InputAction.CallbackContext context)
{
// Get the mouse position from the input action
mousePosition = context.ReadValue<Vector2>();
}
private void OnMouseClickPerformed(InputAction.CallbackContext context)
{
// Check if the left mouse button is clicked
isMouseClicked = context.ReadValueAsButton();
}
private void Update()
{
// Use the mouse position and click input in your game logic
if (isMouseClicked)
{
Debug.Log("Mouse clicked at position: " + mousePosition);
}
}
}
In this example, the MouseInputHandler class is a MonoBehaviour that handles mouse input using the new Input System. Here's how it works:
-
The OnEnable method is called when the script is enabled. It subscribes to the performed event of the mouse position and left button input actions using the Mouse.current property.
-
The OnDisable method is called when the script is disabled. It unsubscribes from the performed event of the mouse position and left button input actions to avoid memory leaks.
-
The OnMousePositionPerformed method is called whenever the mouse position changes. It reads the mouse position value from the input action's context using context.ReadValue<Vector2>() and stores it in the mousePosition variable.
-
The OnMouseClickPerformed method is called whenever the left mouse button is clicked. It reads the button state from the input action's context using context.ReadValueAsButton() and stores it in the isMouseClicked variable.
-
In the Update method, you can use the mousePosition and isMouseClicked variables to perform game logic based on the mouse input. In this example, it simply logs a message to the console when the left mouse button is clicked, along with the current mouse position.
Make sure to attach this script to a GameObject in your Unity scene to enable mouse input handling.
Note: Before using the new Input System, ensure that you have set up the Input System package in your Unity project and have created the necessary input actions in the Input Action Asset.