- Home /
[UNET] Dynamically position NetworkStartPosition Gameobjects
Hi,
I am trying to dynamically change the position and amount of the NetworkStartPosition objects in my game scene depending on the max players set in the Network Lobby Manager. The idea is I will have matches that will allow either 2, 3 or 4 players and I want the spawn positions to be positioned around a large circle in my scene as per the image below respectively.
Can this be done on an Awake() method or OnStartServer() of a 'Spawner' object and then use the RoundRobin spawning method? I guess I could load a different scene depending on the Max Players but that doesn't seem like the best way of doing it.
I would really appreciate any help or suggestions.
Does anyone have an idea of how I can instantiate NetworkStartPosition Gameobjects on level start and use the round robin spawn method to spawn my players?
Answer by pankajb · May 09, 2016 at 05:21 PM
Something like this should work... just set number of players and call generateplayers() function somewhere
int NumberOfPlayers;
Vector3 playerPosition;
float radiusOfOuterCircle;
void GeneratePlayers(){
for (int i = 0; i < NumberOfPlayers; i++) {
float positionOfPlayerOnOuterCircle = i*1.0f / NumberOfPlayers;
//converting it to PI value Mathf.PI*2 ~= 6.28
float Angle = positionOfPlayerOnOuterCircle * Mathf.PI * 2;
float X_position = Mathf.Sin (Angle) * radiusOfOuterCircle;
float Y_position = Mathf.Cos (Angle) * radiusOfOuterCircle;
Instantiate (yourPlayerPrefab, new Vector3 (X_position, Y_position, 0), Quaternion.identity);
}
}
Hey, Thank you for the response. That is an awesome method that I will probably use, but it doesn't answer my specific question around UNET. Does anyone know if I can alter this method to instantiate NetworkStartPosition prefabs on the server before any clients connect?
Answer by Kazhar · Feb 24, 2017 at 09:50 AM
I managed to do this by dynamically generating the NetworkStartPositions. Attach this script to an empty gameObject on your scene:
public class DynamicStartPositions : MonoBehaviour
{
void Awake ()
{
int count = NetworkLobbyManager.singleton.maxConnections;
for (int i = 0; i < count; i++) {
float slice = 2 * Mathf.PI / count;
float angle = slice * i;
float x = Mathf.Cos (angle) * GameManager.arenaRadius;
float y = Mathf.Sin (angle) * GameManager.arenaRadius;
var go = Instantiate (new GameObject (), new Vector3 (x, y, 0.0f), Quaternion.identity);
go.transform.parent = this.transform;
go.AddComponent<NetworkStartPosition> ();
}
}
}
Your answer
Follow this Question
Related Questions
Spawning help 1 Answer
Networking HLAPI Spawning Objects 2 Answers
Random spawnpoint where only one prefab can spawn! 1 Answer
[Help] How Do I Randomly Spawn Game Objects On Specific Coordinates? 3 Answers
how to "search" for a spawn point 0 Answers