Hey everyone, I am currently experiencing an issue with my code which finds the mouse position in order to place prefabbed objects in my game (It works in a grid placement system).
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlowScript : MonoBehaviour
{
[SerializeField]
private GameObject finalObject; //The object which is created upon clicking the mouse
[SerializeField]
private Vector2 mousePos;
[SerializeField]
private LayerMask allTilesLayer;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //This line is the issue
RaycastHit2D rayHit = Physics2D.Raycast(mousePos, Vector2.zero, Mathf.Infinity, allTilesLayer);
if (rayHit.collider == null)
{
Instantiate(finalObject, transform.position, Quaternion.identity);
}
}
}
}
The issue i’m having is, In my game the camera follows my player. For some strange reason the above code is not finding my mouse position but is finding the camera position. this means whenever i click to place an object, the object is placed where my character is standing and not where my mouse is positioned. Any help would be greatly appreciated.
I have included photos of my camera and game object which houses the script in my inspector.
Many thanks.