ScreenToWorldPoint not working correctly.

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.


Well, you are using a perspective camera, that might be the problem.

2 Likes

You are Instantiating using the Script’s transform position, and that’s going to be the parent’s position, always, so try changing that, to the mouse world position:

Instantiate(finalObject, mousePos, Quaternion.identity);
1 Like

Thank you very much, that solved it. Many thanks

Just wanted to add that using raycast to find if 2D colliders are overlapping a point in space is awkward, especially passing a zero direction vector using infinity as distance. Just use OverlapPoint, which will be quicker and you won’t have to pass odd values to it.