I am trying to get a object to spawn at mouse position in unity 2d whenever I click, but none of the objects are showing. It adds new clones in the hierarchy, but just not showing.
Here Is the script for the game controller object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gamecon : MonoBehaviour
{
public GameObject square;
public void Start()
{
}
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 spawnpos = Camera.main.WorldToScreenPoint(Input.mousePosition);
GameObject g =Instantiate(square, (Vector2)spawnpos, Quaternion.identity);
}
}
}
I cant find any answers on the web that apply to my situation. Thanks for help.
CodePudding user response:
The solution is to use the ScreenToWorldPoint method and not the WorldToScreenPoint because what you need is the world position to spawn your object.
Use the following code:
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 spawnpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
GameObject g =Instantiate(square, (Vector2)spawnpos, Quaternion.identity);
}
}