Question by
ahsanmoindev · Mar 24, 2021 at 08:19 PM ·
2dinstantiateprefabgrid
How do I fix 2d Grid Instantiating?
I am trying to make a 2d grid where if you click on a grid square it instantiates a turret prefab to the mouse x position. The script detects that you are clicking but not that you clicked on a gameObject.
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurretSpawner : MonoBehaviour
{
[SerializeField] private GameObject turret;
[SerializeField] private GameObject turret1;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mousePos2D = new Vector2(cursorPos.x, cursorPos.y);
RaycastHit2D hit = Physics2D.Raycast(mousePos2D, Vector2.zero);
if (hit.transform != null)
{
Debug.Log(hit.transform.gameObject.name);
Debug.Log(hit.transform.gameObject.name);
if(hit.transform.gameObject.tag == "GridObject")
{
if (cursorPos.x >= 0)
{
Instantiate(turret, new Vector3(cursorPos.x, 5 + 11, 0), Quaternion.identity);
}
else
{
Instantiate(turret1, new Vector3(cursorPos.x, 5 + 11, 0), Quaternion.identity);
}
}
}
}
}
}
Comment
When I click it it does not return anything in the debug area I think the transform is null or something.
Best Answer
Answer by ahsanmoindev · Mar 25, 2021 at 12:39 PM
I had to give it a BoxCollider2D. I set it to IsTrigger so it had no collisions and it worked. :D