How to create Obstacles dynamically before the player like in Temple run.

Hello ,

I have created a player that runs forever until it hits any obstacle. The game has some buildings,cars .,etc. Now I want to spawn some Obstacles dynamically before the player.

To do this I have created an Empty GameObject called PlayerFollower and added it as a Child to the Player GameObject. So when ever the player moves forward the PlayerFollower also moves.

The script I have attached to the Player is :

using UnityEngine;
using System.Collections;

public class playerFollower : MonoBehaviour {

public Transform Player;
private GameObject Obstacle;
public GameObject Hurdles;
private Transform rotation;
// Use this for initialization
void Start () {
	
	InvokeRepeating("createHurdles", 2, 7.0F);
	
}


void createHurdles()
{	
	
	
	

	Vector3 playerPos = Player.position;

	
	Vector3 ObstaclePosition = transform.position;

	
	ObstaclePosition.y = 1;
	Obstacle = Instantiate(Resources.Load("Obstacles/Hurdle"),ObstaclePosition,transform.rotation) as GameObject;
	Obstacle.transform.rotation = Player.transform.rotation;
	Debug.Log("rotation :"+Obstacle.transform.rotation);
	Obstacle.transform.parent = Hurdles.transform;

	
	Debug.Log("Hurdle created at :"+ObstaclePosition);
	
}

// Update is called once per frame
void Update () {
	
	
	
	float dist = Vector3.Distance(Player.position,transform.position);
	Debug.Log("Distance :"+dist);

}

}

Also I want to destroy the Obstacle after the player has crossed it. I want to do this in the Update function above :

If(dist <= 3.0f)
Destroy(ObstacleObject)

But this is not an effective solution , because the distance is sometimes not less than 3.0f and if I give something like >5.0f , The Obstacle destroys in advance, before the player . Is there any better solution.

Also there are buildings , in behind , If i move the PlayerFollower also moves and it is creating Obstacles inside the buildings , how to overcome this ?

I had this issue in a game I was making, the way I resolved it was by creating the obstacles in the path maker and not relative to the player. This way the obstacles won’t be created inside buildings.

I’m not sure what type of path the player will be following but I’m guessing you have a made a system to create one randomly. Just add the obstacle spawning there.

I would recommend creating a pool of your different obstacle game objects and rather than using Instantiate and Destroy, just enable and disable them when you want to use them. It’s best to avoid using Instantiate and Destroy when possible as they can effect performance when used frequently, especially on mobile platforms.