I am making a 3D super smash bros style game with two players controlling WASD or Arrow keys. My game has a few prefab characters(2 versions for each one- ArrowKeys and WASD).
I want to make a character selection, but both versions of characters have specific version based tags(either WASDPlayer or ArrowKeysPlayer) and they refer to each other upon start().
Additionally, many other scripts in the scene use the tags to find both characters in the scene.
If I was to instantiate the character chosen in the character selection scene I am worried that it will instantiate after start runs, leading to many scripts not able to find the characters.
I also thought about making all characters in the event selection scene don’t destroy on load and upon clicking select all the other characters(except the 2 chosen ones) are deleted.
What are your thoughts about the correct way to implement it?
Hmm… I believe that instantiate has some delay, so how would that factor into using awake, as what if the character isn’t fully instantiated by the time start runs?
For anyone stuck on this issue, I instantiated the characters in start:
private void Start()
{
// Check if the prefabs are assigned
if (selectedPlayer1Prefab == null || selectedPlayer2Prefab == null)
{
Debug.LogError("Selected player prefabs are not assigned.");
return;
}
// Instantiate the selected players at designated spawn points
Instantiate(selectedPlayer1Prefab, player1SpawnPoint, Quaternion.identity);
Instantiate(selectedPlayer2Prefab, player2SpawnPoint, Quaternion.identity);
Debug.Log("Players spawned successfully in the new scene.");
// Trigger the event to notify other scripts
OnPlayersSpawned?.Invoke();
}
and for scripts that used the tags:
private void OnEnable()
{
// Subscribe to the OnPlayersSpawned event
PlayerSpawner.OnPlayersSpawned += InitializePlayers;
}
private void OnDisable()
{
// Unsubscribe from the event when this script is disabled
PlayerSpawner.OnPlayersSpawned -= InitializePlayers;
}
private void InitializePlayers()
{
// Get players by tag now that they are guaranteed to be instantiated
player1 = GameObject.FindGameObjectWithTag("WASDPlayer").transform;
player2 = GameObject.FindGameObjectWithTag("ArrowKeysPlayer").transform;
if (player1 == null || player2 == null)
{
Debug.LogError("Players not found by tag.");
return;
}
}