Help with spawning Prefabs that go towards a player
I need some writing a script that would help me spawn prefabs that move towards a player.
i have already look at http://answers.unity3d.com/questions/179605/moving-an-object-towards-another-moving-object.html and http://answers.unity3d.com/questions/560190/make-item-spawn-at-a-empty-game-object-location.html
and they dont seem to help me
Answer by Zoogyburger · Feb 27, 2016 at 04:57 AM
Here's a spawner script:
{
public float spawnTime = 5f;
//The amount of time between each spawn.
public float spawnDelay = 3f;
//The amount of time before spawning starts.
public GameObject[] enemies;
//Array of enemy prefabs.
public Vector3 enposition;
void Start ()
{
//Start calling the Spawn function repeatedly after a delay.
InvokeRepeating("Spawn", spawnDelay, spawnTime);
}
void Spawn ()
{
//Instantiate a random enemy.
int enemyIndex = Random.Range(0, enemies.Length);
Instantiate(enemies[enemyIndex], enposition, transform.rotation);
}
Here's a enemy move toward player script
public Transform Player;
public float speed = 2f;
private float minDistance = 0.2f;
private float range;
void Update ()
{
Player = GameObject.FindWithTag ("Player").transform;
range = Vector2.Distance(transform.position, Player.position);
if (range > minDistance)
{
Debug.Log(range);
Player = GameObject.FindWithTag ("Player").transform;
transform.position = Vector2.MoveTowards(transform.position, Player.position, speed * Time.deltaTime);
}
}
What you do is attach the spawner script on an empty gameobject at the position you want the enemy to spawn and drag your prefab (with the enemy move toward player script on it) into the slot in the inspector on the spawner.
Answer by andyipod1437 · Feb 27, 2016 at 02:06 PM
is there any way i get the enemy to spawn the all over the out side and come towards the Player. and When i ran your srcipt it only spawn the enemy once . Thanks @Zoogyburger
Just duplicate the empty gameobject that has the spawner script on it and move them to the position that you want the enemies to spawn from. If you attach my second script to your enemy prefab they will move toward the player. Inside the inspector on the spanwer you can see two variables, spawnTime and spawnDelay. If you make those variables low, the enemies will spawn faster.