So im making a script for my tower defense game, but im trying to figure out how to prevent something from placing if there is a gameobject in the way. Here is my script.
public GameObject NormalTower;
public GameObject Tower;
private Camera cam => Camera.main.GetComponent<Camera>();
Vector3 mousepos => new Vector3((Mathf.Floor(cam.ScreenToWorldPoint(Input.mousePosition).x)) + 0.5f, (Mathf.Floor(cam.ScreenToWorldPoint(Input.mousePosition).y)) + 0.5f, 0);
if (Tower != null)
Tower.transform.position = mousepos;
Tower = null;
public void TowerPlacee()
= Instantiate(NormalTower, mousepos, transform.rotation);
Hey there, welcome to the forum.
There are some things that i’d suggest here.
First up, to solve your general issue you probably can use a raycast. So basically when you call your
PlaceTower function you just do a raycast
if(Physics.RayCast(cam.transform.position, mousepos - cam.transform.position, out RayCastHit hit))
//instantiate tower here
(code above not tested and written from the back of my head - syntax is probably not correct - take is as pseudo code please)
This however could lead to the problem that your towers could be placed too close to each other.
Is there a grid that you place your towers on? If yes then you could solve the issue by raycasting the center of the tile that you currently aim at. If not you might have to do a boxcast/spherecast instead (documentation can show you how to do this)
apart from that - please never do something like this:
This is the worst way you can waste performance and i am not sure what it even achives for you. Please let me know and we can find a better way to do this.
FindObject... calls of any kind should at most be used in Start/Awake for initialization purposes as they are slow - especially if there is a lot of objects in the scene.