- Home /
Spawn Random Enemy
I want to make a script that will pick one game object out of a few and instantiate it. also, i want it to be able to change the number of gam objects that i can assign with a variable, so that if i come up with another enemy, i can just change the variable. C# please!
you should look at arrays in unity and the Random.range method. understanding the 2 will give you the power to do as you ask.
Answer by kamgru123 · Oct 16, 2014 at 08:44 PM
Something along this way should do what you ask for. In the editor add gameobjects to the array, then when you want to spawn the enemy just call SpawnRandom().
class Spawner : MonoBehaviour
{
public GameObject[] objects;
public void SpawnRandom()
{
Instantiate(objects[UnityEngine.Random.Range(0, objects.Length - 1)]);
}
}
Sweet, dude! This stuff is pure magic! Really appreaciate your hel. Big step in my game.
I confirm: pure magic. Well done and thanks too !
This deserves to have a 100 votes so to be easily found on the web ^^"
To also have a random position, I used it this way :
public GameObject[] objects; // The prefab to be spawned.
public float spawnTime = 6f; // How long between each spawn.
private Vector3 spawnPosition;
// Use this for initialization
void Start ()
{
// Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
void Spawn ()
{
spawnPosition.x = Random.Range (-17, 17);
spawnPosition.y = 0.5f;
spawnPosition.z = Random.Range (-17, 17);
Instantiate(objects[UnityEngine.Random.Range(0, goodie.Length - 1)], spawnPosition, Quaternion.identity);
}
Answer by PixelZebra · May 11, 2015 at 11:06 PM
Hi there!
I really love this script. But being a beginner in the programming scene, I must ask, can someone tell me how to make my enemies move on an X axis upon their apparence on screen ? Thanks in advance :)
How do you mean? If you want them to be instantiated on a random place in one axis and INA specific place on the other(s) then just instantiate it as a variable and set the variable's position on the random axis to Random.Range($$anonymous$$imum, maximum).
If I totally misunderstood that (I doubt I didn't) then post a comment (not an answer like with this question) and I can help you. I asked this a WHILE ago so I know a lot more now than I did before.
float maxspeed = 5;
Void Update(){
Vector3 pos = transform.position; // this gets the current position
pos.x += maxspeed * Time.deltaTime;
transform.position = pos; }
Answer by OanhDv · Jul 17, 2017 at 02:51 AM
how to make spawn enemy with position camera
/
You will put this script to camera . It will spawn enemy on click spacebar public GameObject enemy;
void Update() {
if(Input.GetKeyDown(KeyCode.Space)) {
`Spawn();
`}
}
void Spawn() {
Vector3 pos = transform.position; // gets current location
Instantiate(enemy, pos, Quaternion.identity);
}