Skip to main content

Is my collision-free location script working?

I've recently been learning C# and I wanted to take one of my 2D tutorials to Unity.

I reached a step where I need to spawn my new sprite into a collision free location. I've followed direction - generated random location, calulating vector2s using the location and collider, and then used a while loop to check Physics2D.OverlapArea using my 2 vectors

But, because I'm still only just learning c#, I'm finding it difficult to know if I have actually written my code correctly. Is there any simple way of being able to figure this out? Using Debug or something?

Vector3 spawnLocation = new Vector3 (Random.Range (minSpawnX, maxSpawnX),
                                     Random.Range (minSpawnY, maxSpawnY),
                                     -Camera.main.transform.position.z);
Vector3 spawnPoint = Camera.main.ScreenToWorldPoint (spawnLocation);
Vector2 lowerLeftCorner = new Vector2 (spawnPoint.x - teddyBearColliderHalfWidth,
                                       spawnPoint.y - teddyBearColliderHalfHeight);
Vector2 upperRightCorner = new Vector2 (spawnPoint.x + teddyBearColliderHalfWidth,
                                        spawnPoint.y + teddyBearColliderHalfHeight);
while (Physics2D.OverlapArea (lowerLeftCorner, upperRightCorner) != null) 
       {
            spawnPoint.x = Random.Range(minSpawnX, maxSpawnX);
            spawnPoint.y = Random.Range(minSpawnY, maxSpawnY);

            lowerLeftCorner = new Vector2 (spawnPoint.x - teddyBearColliderHalfWidth,
                                           spawnPoint.y - teddyBearColliderHalfHeight);
            upperRightCorner = new Vector2 (spawnPoint.x + teddyBearColliderHalfWidth,
                                            spawnPoint.y + teddyBearColliderHalfHeight);
        }
Debug.Log (Physics2D.OverlapArea(lowerLeftCorner, upperRightCorner));

I was trying to use a debug at the end there, but it doesn't seem to continue running every single time that there's a spawn, so I am still unsure if it is working. I'm terribly sorry for my nooby code. Feel free to direct to me some place else if you feel I need to do so.