Hello everyone!
I’m trying to write a script that instantiates a square prefab at a random location on screen. If the space is already occupied by a previously instantiated square, it should just write something in the console. Here’s the code I’ve written:
public void SpawnSquares(int difficulty){
float R1=Random.Range(25.0f,_screenWidth);
float R2=Random.Range(25.0f,_screenHeight);
_overlapA=new Vector2(R1-50f,R2+50f);
_overlapB=new Vector2(R1+50f,R2-50f);
if(Physics2D.OverlapArea(_overlapA,_overlapB,layermask,Mathf.Infinity,Mathf.Infinity)==null){
_position=Camera.main.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(R1,R2,10));
Instantiate(Resources.Load("Square",typeof (GameObject)),_position,Quaternion.identity);
}
else{
Debug.Log("avoided collision");
}
}
The layermask variable is set layermask=1<<9; because all the squares are located on layer 9.
What I expected this to do was generate a random location and modify _overlapA and _overlapB to account for the size of the squares, then check if there are any colliders in that certain area. If there are not (OverlapArea==null) then it should spawn a new square at that position. If the space is occupied just write to console.
What is actually happening? The execution never branches off on else, so that means Physics2D.OverlapArea(_overlapA,_overlapB,layermask,Mathf.Infinity,Mathf.Infinity) always returns null. However, after calling SpawnSquares() around 10 times the screen is pretty much filled up with squares so it should at least detect one collider.
What am I doing wrong? My project has stalled for the last two days because I can’t seem to solve this issue, so any help would be greatly appreciated.
Thanks for your time!