How to spawn a prefab in a cone in front of player?

I am making a game when the player is constantly moving up the screen. I want to create an enemy player a specific distance in front of the player, at a random angle from where the player is currently facing (a 45 degree cone). I thought this would be easy to do, but I am really struggling.

I can create the prefab directly in front of the player (2d like game) with the following:

obj = Instantiate(meteorSmall, pos + ship.transform.up * spawnDistance, Quaternion.identity);

This however doesn’t allow me to specify an offset front the player. I have also tried using the Mathf.sin and Mathf.cos functions but again I just can’t seem to make it work.

Any ideas?

Idea here is that we are facing transform.rotation, so combine that with a local random +/-45 to get the new angle, then “shoot” that way to get final position. Not tested, but the general idea has been used a lot:

// random left/right +/-45 Y angle:
Quaternion randAng = Quaternion.Euler(0, Random.Range(-45,45), 0);

// NOTE: this is 45 left/right from due north

// combine +/-45 with our current facing, to get +/-45 FROM US:
randAng = transform.rotation * randAng; // this might be backwards

// use that angle to get a distance from us:
Vector3 spawnPos = transform.position + randAng * Vector3.forward * 15;

It takes a while to get used to how times(*) combines to rotations, and also applies a rotation to a Vector. Then trying to remember if you want it on local or global axis. Can use Sin/Cos, but quaternions do all that math for you.

This should work. Create an empty gameObject called SpawnPoint, make it a child of the ship, place it at Transform(0, 0, 1) to the ship, then move that around with RotateAround, then use it’s position as the spawn point :

function SpawnObject() 
{
	spawnPoint.localPosition = transform.forward * spawnDistance;
    spawnPoint.RotateAround( ship.transform.position, ship.transform.up, Random.Range( -45.0, 45.0 ) );
	spawnPoint.RotateAround( ship.transform.position, ship.transform.right , Random.Range( -45.0, 45.0 ) );
	var obj : Transform = Instantiate( meteorSmall, spawnPoint.position, Quaternion.identity );
}