Spawning Randomly

I am trying to make a space shooter game in Unity. This is my first attempt at making a game in Unity. I figured out how to make my enemies move back and forth in the game, but I don’t know how to make them spawn randomly.

Here is my code for the enemy movement:

using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour
{
private float c = 4;

void Update ()
{
transform.position = new Vector2 (3 * Mathf.Sin (Time.time + c), 7);
}
}

And here is my code for random spawn locations for my 2d game:

using UnityEngine;
using System.Collections;

public class Spawn : MonoBehaviour {

public Vector2 spawnValues;
public GameObject Enemy;

void start ()
{
SpawnWaves ();
}

void SpawnWaves ()
{
Vector2 spawnPosition = new Vector2 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (Enemy, spawnPosition, spawnRotation);
}
}

Can someone either edit my code or give me new code about how to make random spawn locations for enemies that then have to move back and forth?

Please use code tags.

For a Space invaders type movement?

After you spawn the enemy, each enemy should have there own script, something like AI_Control, where you tell them what to do :stuck_out_tongue:

1 Like

Create some empty game objects in the scene. Then give them a tag of spawnpoint. In your code find these gameobjects with the tag spawnpoint in a gameobject array then instantiate your gameobjects randomly at the spawnpoint positions.
int rand = Random.Range(0, GameOArray.Length).
Then instantiate it.

1 Like

Thanks, I will try this out

Try this out and if you still cant work it out ill give you an example.