Proper way to get references to playerspawns?

I made a quick prefab so I can easily add playerspawns to the levels. However, how do I get the reference to these playerspawns? I don’t want to use tags (unless you can convince me otherwise) because those loop through all of the gameobjects, slowing down the loading of a new level unnecessarily.

Every playable level has one or more of these prefabs.

I can’t use the GameSettings singleton class because I can’t drag the spawns from the level into the singleton (which is only created in the first scene, and then never destroyed). How does one do this properly?

using UnityEngine;
using System.Collections;

public class PlayerSpawn : MonoBehaviour {

   #region Members
  public string GizmoTexture = "PlayerSpawnGizmo.png";
  public float Icon_Y_Offset = 1;
  private const float PLAYER_HEIGHT = 3;
  private const float FACING_ARROW_LENGTH = 1.5f;
   #endregion

  void OnDrawGizmos()
  {
  Gizmos.DrawIcon(transform.position + (Icon_Y_Offset * Vector3.up), GizmoTexture);
  Gizmos.color = Color.yellow;
  Vector3 cube_center_addition = (PLAYER_HEIGHT / 2) * Vector3.up; // A vector3 that represents half the player-size upwards.
  Gizmos.DrawWireCube(transform.position + cube_center_addition, new Vector3(1, PLAYER_HEIGHT, 1));
  Gizmos.DrawLine(transform.position + cube_center_addition, transform.position + (FACING_ARROW_LENGTH * Vector3.forward) + cube_center_addition);
  }
}

Note that the same problem applies to many other prefabs like EnemySpawners. I place, let’s say 5 EnemySpawners in some towerdefense game in the level. And every 10 seconds I need to retrieve the reference to those spawners so that I know where to spawn them, what direction they face, etc.

Or should I create a new singleton like public class LevelInfo that is recreated in every level? And that I drag that onto an empty gameobject in every level?

What if they registered themselves to the appropriate system or list?

void Awake()
{
     GameManager.AddSpawnPoint(this.gameObject);
}
1 Like

Why didn’t I think of that… That is a fantastic idea!

Or send a PlayerSpawned event when they spawn. Then any script can listen to that.

Events could work. But in general I don’t want to trigger every spawn for just one player or one enemy. In most of the cases I only need to address one single spawner (or other object) out of a list of many. I just want to say:

spawnplayer(spawners.random, boltconnection)

Now if each spawner just registers itself on Awake() then I have a guaranteed reference to that list without having to add something myself to every level.