I have this code for spawning enemies in my space shooter game and the code works in MonoDevelop, but does not do what I want in Unity. This is probably a very simple and easy thing to figure out, but I am really new at coding and this stuff still poses a challenge to me.
The code I have is partially mine, partially someone else’s who was kind enough to help me on this forum, but the code he implemented is code I do not completely understand. Here is the code,
using UnityEngine;
using System.Collections;
public class Spawn : MonoBehaviour
{
public GameObject [] spawnpoints;
public GameObject Enemy;
void start ()
{
spawnpoints = GameObject.FindGameObjectsWithTag("Spawnpoint");
GameObject spawn = spawnpoints [Random.Range (4, spawnpoints.Length )];
Instantiate (Enemy, spawn.transform.position, spawn.transform.rotation);
}
}
The line GameObject spawn = spawnpoints [Random.Range (4, spawnpoints.Length )]; is the section I cannot grasp. I understand that I am setting a game object, spawn, equal to my array spawnpoints, but I don’t understand anything about that section beyond this. Can someone explain this line to me and maybe tell me how to get this code actually working in Unity?
this line sets a new GameObject named spawn to one of the Spawnpoints defined in the inspector, this is done by using Random.Range and SpawnPoints.length, .length gets the length of the array which is done by added objects to it in the inspector
// this Spawns enemys, by instantiating a prefab, creating clones and sets there spawn position to the Transform and Rotation which is defined and stored in the Gameobject spawn
Thanks for the help! So I put the script on an empty game object and then set the size of the array to 3 in the inspector. After that I dragged three empty game objects into the array whose location matches where I want the enemy to spawn. But it still does not work.
Here is a screenshot of Unity. What am I still doing wrong?