Skip to content

Spawning the Player

  • Goal: We want to spawn our player prefab at a random spawn point, designated by a Unity tag,
  • Usage:
    1. Create a Unity tag that will be used to identify your potential spawn points.
    2. Attach the script to any GameObject outside of the dungeon hierarchy.
    3. In the inspector, set the RuntimeDungeon to the dungeon generator you want to use and set PlayerPrefab to the player prefab you want to spawn. Set the SpawnPointTag to the tag created earlier.
    4. 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;
        }
    }
}