Hello Everyone
I am currently busy with an endless runner. I have a base "Tunnel" prefab to prevent the user from falling off the map. This is then instantiated every time an object with tag X enters the prefab. Now, as soon as the user exits said prefab(via trigger), it is destroyed.
My problem is with the obstacles, or to be more precise, how to destroy them. I have a simple obstacle(beautiful cubes!!), which is a prefab. I instantiate it at random locations(to put it briefly). I want to know how I could destroy these obstacles at the same time the "Tunnel" gets destroyed. I have tried parenting the obstacles to the tunnel, but that seems to alter the prefab itself. I also tried putting them in a list, and also creating a new object, which I then parent the obstacles to, but none of these solutions work.
Any help?
Code:
public class LevelGenerator : MonoBehaviour {
public GameObject BaseBlockPrefab;
public GameObject ObstaclePrefab;
Collider col;
void Start ()
{
col = GetComponent();
}
private void OnTriggerEnter(Collider collider)
{
CreateNewBlock(collider);
}
private void OnTriggerExit(Collider other)
{
Destroy(gameObject);
}
private void CreateNewBlock(Collider collider)
{
if (collider.CompareTag("Hoverboard"))
{
//Instantiates segment and sets its name(as not to have excessively long names)
var instance = Instantiate(
BaseBlockPrefab,
new Vector3(0, 0, transform.position.z + col.bounds.size.z),
Quaternion.identity
);
instance.name = "Base Wall";
CreateObstacles(instance.GetComponent().bounds.center.z);
}
}
private void CreateObstacles(float instantiatedSegmentZ)
{
var PositionList = new List { -2.5f, 0f, 2.5f };
int NumberOfObstacles = Mathf.FloorToInt(UnityEngine.Random.Range(1, 3));
for (int i = 0; i < NumberOfObstacles; i++)
{
var RandomIndex = Mathf.FloorToInt(UnityEngine.Random.Range(0, PositionList.Count));
var obstacleInstance = Instantiate (
ObstaclePrefab,
new Vector3(PositionList[RandomIndex], 0, instantiatedSegmentZ),
Quaternion.identity
);
PositionList.RemoveAt(RandomIndex);
}
}
}
↧