At last, I had to try with a similar code, I think the previous one worked just fine but it didn’t snap cuz I made a mistake somewhere I’ll check and edit if needed.
using UnityEngine;
public class GetACaptus : MonoBehaviour
{
[SerializeField] GameObject captus;
CaptusSpawner inputs;
private void Awake()
{
inputs = new CaptusSpawner();
}
private void OnEnable()
{
inputs.Enable();
}
private void OnDisable()
{
inputs.Disable();
}
private void Start()
{
inputs.PlayerInput.Clicked.started += _ => DetectObject();
}
private void DetectObject()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(inputs.PlayerInput.Position.ReadValue<Vector2>());
Vector2 gridPos = SnapToGrid(mousePos);
RaycastHit2D hits2D = Physics2D.Raycast(gridPos, Vector2.zero);
if (hits2D.collider != null)
{
Debug.Log("2D hit" + hits2D.collider.tag);
Instantiate(captus, gridPos, transform.rotation);
}
}
private Vector2 SnapToGrid(Vector2 rawWorldPos)
{
float newX = Mathf.RoundToInt(rawWorldPos.x);
float newY = Mathf.RoundToInt(rawWorldPos.y);
return new Vector2(newX, newY);
}
}
I don’t know if is weird how this is workin without using UnityEngine.InputSystem;
I attached the scrip to the object with the collider where I wanted to click.
And to look for the mous posicion I had to add that here.