Checking to see if a position is occupied by a GameObject

Basically i’ve got a top down 2d view in which the player can move around. Enemies randomly spawn and will follow the player until they reach an adjacent square, where they will stop and spend subsequent “turns” attacking the player.
All enemies and the player take up 1 unit of space.
That part all works.

What I would like is when the player attempts to move into a square, it first checks if that square is occupied by an enemy game object. If it is occupied, the player will remain in their own square and the attack code will be carried out against the enemy.
If the square is empty the player moves as normal.
So basically is there an easy way to check if a position is occupied by a gameobject?
And then I could do:

if(squareIsOccupied){
// find out what GameObject is occupying it
 // Carry out attack code against GameObject in that square.
}
else{
 // Carry out movement code.
}

raycast to that position, gather information from the hit.collider.gameObject http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html

2 Answers

2

This is already answered here:

But in case:

var spawnPoint:Vector3 = square.position;
var hitColliders = Physics.OverlapSphere(spawnPoint, 1);//1 is purely chosen arbitrarly
if(hitColliders.Length > 0) //You have someone with a collider here

is there a 2D version of this?

I think you can use this: var hitColliders = Physics2D.OverlapCircle(spawnPoint, 1);//1 is purely chosen arbitrarly