How can I spawn an enemy "behind the nearest corner"?

Hey guys! How can I instantiate a object at the nearest corner so he won’t just appear from dust?

It’s too difficult to figure out what a corner is at runtime so you need to pre-mark all your corners. That is place empty game objects at all the possible spawn points. Then you can put them in an array and move through them easily.

var spawnPoints : Transform[];
var enemy : Transform;

var player : Transform;

function Start () {
     player = GameObject.FindWithTag("Player");
     InvokeRepeating("SpawnEnemy" , 5 , 5);
}

function SpawnEnemy () {
    var idealSpawn : Transform = spawnPoints[0];
    var curDist = Vector3.Distance(idealSpawn.position , player.position);
    //This is just a basic search algorithm.  We test every item in the array to see if it is better suited than the one's before it.
    //We assume that the first point is the best then we try and prove otherwise.

    for ( var i = 1 ; i < spawnPoints.Length ; i++) {
        //No need to test the first point.
        if (Vector3.Distance(spawnPoints*.position , player.position) < curDist ) {*

//Are we closer than the old point?
if( Physics.LineCast(player.position, spawnPoints*.position) ) {*
//Is there something between the player and the point.
idealSpawn = spawnPoints*;*
curDist = var curDist = Vector3.Distance(idealSpawn.position , player.position);
}
else if ( Vector3.Dot( player.forward , (spawnPoints - player.position).normalized ) < 0) {
//or is the point behind the player?
idealSpawn = spawnPoints*;*
curDist = var curDist = Vector3.Distance(idealSpawn.position , player.position);
}
}
}
Instantiate (enemy , idealSpawn , Quaternion.Identity);
}
This should pretty much do what you want. Let me just warn you about 2 oversights that I deliberately made:
1. There are quicker ways of doing distance checks than with Vector3.Distance(). Its just the easiest to read so I put it in there and you can change it if you want.
2. Possibly the more important one. This method breaks down if the character is closest to the “0” element in the array and he is already looking at it. It doesn’t take that much effort to fix it. Just do a final check at the end to make sure that if the first element was the “ideal” spawn that it isn’t visible.