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 actions
Mouse.current.position.performed += OnMousePositionPerformed;
Mouse.current.leftButton.performed += OnMouseLeftButtonPerformed;
}
private void OnDisable()
{
// Disable the mouse input actions
Mouse.current.position.performed -= OnMousePositionPerformed;
Mouse.current.leftButton.performed -= OnMouseLeftButtonPerformed;
}
private void OnMousePositionPerformed(InputAction.CallbackContext context)
{
// Get the mouse position from the input action
mousePosition = context.ReadValue<Vector2>();
}
private void OnMouseLeftButtonPerformed(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:
-
We define a MouseInputHandler class that inherits from MonoBehaviour.
-
We declare two private variables: mousePosition to store the current mouse position and isMouseClicked to track whether the left mouse button is clicked.
-
In the OnEnable method, we subscribe to the performed event of the Mouse.current.position and Mouse.current.leftButton input actions. This allows us to receive callbacks when the mouse position changes or the left mouse button is clicked.
-
In the OnDisable method, we unsubscribe from the performed event of the mouse input actions to avoid memory leaks.
-
The OnMousePositionPerformed method is called whenever the mouse position changes. We read the mouse position value from the input action using context.ReadValue<Vector2>() and store it in the mousePosition variable.
-
The OnMouseLeftButtonPerformed method is called whenever the left mouse button is clicked. We read the button state using context.ReadValueAsButton() and store it in the isMouseClicked variable.
-
In the Update method, we can use the mousePosition and isMouseClicked variables to perform game logic based on the mouse input. In this example, we simply log a message to the console when the left mouse button is clicked, along with the current mouse position.
To use this script, attach it to a GameObject in your Unity scene. Make sure you have the new Input System package installed and have set up the appropriate input actions in your project's Input Action Asset.
Remember to handle any necessary game logic or interactions based on the mouse position and click input within the Update method or other appropriate methods in your script.