Spawning the Player
- Goal: We want to spawn our player prefab at a random spawn point, designated by a Unity tag,
- Usage:
- Create a Unity tag that will be used to identify your potential spawn points.
- Attach the script to any GameObject outside of the dungeon hierarchy.
- In the inspector, set the
RuntimeDungeonto the dungeon generator you want to use and setPlayerPrefabto the player prefab you want to spawn. Set theSpawnPointTagto the tag created earlier. - Apply the tag to empty objects placed inside your Tiles. These are the places where the player can spawn.
SimplePlayerSpawner.cs
using DunGen;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SimplePlayerSpawner : MonoBehaviour
{
// The dungeon generator we are using
public RuntimeDungeon RuntimeDungeon;
// The prefab we want to spawn to represent the player
public GameObject PlayerPrefab;
// The tag we are using to identify spawn points
public string SpawnPointTag = "PlayerSpawn";
// Whether we should only spawn on the start tile
public bool StartTileOnly = true;
private GameObject player;
private void OnEnable()
{
RuntimeDungeon.Generator.OnGenerationStatusChanged += OnDungeonGenerationStatusChanged;
}
private void OnDisable()
{
RuntimeDungeon.Generator.OnGenerationStatusChanged -= OnDungeonGenerationStatusChanged;
}
private void OnDungeonGenerationStatusChanged(DungeonGenerator generator, GenerationStatus status)
{
if (status == GenerationStatus.Complete)
SpawnPlayer(generator.CurrentDungeon);
else
{
// Destroy any existing player
if (player != null)
Destroy(player);
}
}
private void SpawnPlayer(Dungeon dungeon)
{
// Determine where the player can spawn
var hierarchyToSearch = (StartTileOnly) ? dungeon.MainPathTiles[0].transform : dungeon.transform;
// Find all valid spawn points (all GameObjects with the appropriate tag) within out chosen search hierarchy
var spawnPoints = FindSpawnPointsInHierarchy(hierarchyToSearch);
// Select one of the spawn points at random
int spawnPointIndex = UnityEngine.Random.Range(0, spawnPoints.Count());
var selectedSpawnPoint = spawnPoints.ElementAt(spawnPointIndex);
// Spawn the player prefab at the target
player = Instantiate(PlayerPrefab, selectedSpawnPoint.position, selectedSpawnPoint.rotation);
}
/// <summary>
/// Search through a transform hierarchy to find any objects with the appropriate tag
/// </summary>
private IEnumerable<Transform> FindSpawnPointsInHierarchy(Transform currentTransform)
{
if (currentTransform.gameObject.CompareTag(SpawnPointTag))
yield return currentTransform;
for (int i = 0; i < currentTransform.childCount; i++)
{
var childTransform = currentTransform.GetChild(i);
foreach (var spawnPoint in FindSpawnPointsInHierarchy(childTransform))
yield return spawnPoint;
}
}
}