Instantiating objects to trail player

Hello everyone,

I’ve been putting off posting a question here until I really have to, but this problem has got me stumped.

I want to instantiate objects at the player’s location but with a delay of a second or two, set by a public variable. They are currently instantiated and are destroyed a few seconds later, thus forcing the player to keep moving or be caught up. These objects will not move or follow the player directly as they are spikes coming out of the ground. I’ll deal with the upward movement of the spikes later, right now I just want to get them instantiating at the right time.

I’ve got the objects instantiating at the right place but they appear immediately under/on/in the player. I’m trying to use ‘yield’ but it only seems to set the delay before the first object is instantiated or the delay between each instantiated object.

Ideally I would like the game to begin, the player to have a timed head start (a public float variable), then the first object is instantiated where the player was. Then wait for a period of time (another public float variable) before instantiating another object but again this will be at the player’s location immediately after the first location.

The end result will be a wave of spikes trailing the player.

Here’s the code I’ve come up with so far…

using UnityEngine;
using System.Collections;

public class GameController2 : MonoBehaviour
{
	public GameObject hazard;
	public int spikeCount;
	public float spikeWait;
	public float chaseWait;

	private GameObject playerTarget;
	private Vector3 targetPos;

	void Start()
	{
		StartCoroutine (SpawnWaves ());
	}
	void Update()
	{
		playerTarget = GameObject.FindGameObjectWithTag("Player");
		targetPos = playerTarget.transform.position;
	}

	IEnumerator SpawnWaves()
	{
		while(true)
		{
			yield return new WaitForSeconds (chaseWait);
			for(int i = 0; i < spikeCount; i++)
				{
					Instantiate (hazard, targetPos, Quaternion.identity);
					yield return new WaitForSeconds (spikeWait);
				}
		}
	}
}

Any help or suggestions where to look would really be appreciated.

If you move line 21 from inside Update() to line 28 (just before the yield), you shoudl fix your problem. It would be a good programming practice to move the declairation of ‘targetPos’ to 26 to keep it local to SpawnWaves().

Alright, I understand your problem better now, it wasn’t so much an issue with the delay, but the position it appeared after the delay.

In that case, it’s as simple as creating a temporary Vector3 to store the position before the delay.

IEnumerator SpawnWaves()
{
       yield return new WaitForSeconds (chaseWait);
       int i = 0;
       while(i < spikeCount)
       {
         i ++;
         Vector3 prevPos = targetPos;
         yield return new WaitForSeconds (spikeWait);
         Instantiate (hazard, prevPos, Quaternion.identity);

       }
}