Spawning something if it is not within another object?

Hi everyone. I am creating a tower defense game in which the player can drag a tower from the purchase bar and then lift the left mouse button to spawn the chosen tower at the mouse position. I have all of that working, so now I am trying to prevent the tower from being spawned on top of other objects like other towers or the purchase bar. I know the fix is probably fairly simple with the Physics2D.overlap, but after following the “Bits&Bobs Unity Tutorial - Overlap Sphere” and looking through other forum posts, I still wasn’t sure what to do to accomplish this. (My programming knowledge is very limited). Any help is appreciated!

Here is my code for the current spawn system:

public GameObject towerActive;

void Start()
{

}

void Update()
{
    Vector2 cursorPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    transform.position = new Vector2(cursorPosition.x, cursorPosition.y);

    if (Input.GetMouseButtonUp(0))
    {
        Instantiate(towerActive, cursorPosition, Quaternion.identity);
        Destroy(gameObject);
    }
}

}

Hi!

So, basically, what you want to do is check if you have any object at your mouse position when instantiating. For that I recommend to use Raycasting, but keep in mind that it only detect objects with Collider component - without it the object will not be detected.

Below an example how it works in 3D. You basically shoot ray from camera to mouse position and it returns true if hits something.

RaycastHit hit;

if(Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity))
    Debug.Log("We did hit something and we don't want to be able instantiate");

I am not too familiar with 2D, but the code below should gave similar behaviour and work properly.

RaycastHit2D hit2D;

Ray ray = cam.ScreenPointToRay(Input.mousePosition);
hit2D = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);

if(hit2D.collider != null)
    Debug.Log("We did hit something and we don't want to be able instantiate");

The cam is the reference to the Camera: public Camera cam;

Let me know if it helps.


Here you can find additional information about Raycasting: Unity - Scripting API: Physics2D.Raycast
Unity - Scripting API: Physics.Raycast

Hey, thanks for answering! I’ll look into this and give it a try in the morning!

This worked great, thank you! I had to use Camera.main instead of a public Camera variable because the inspector wouldn’t let me drag in the main camera for some reason. I also had to switch the != to == because it was giving me the opposite effect. Other than that, this was perfect. Thanks again!!