Home > Net >  Creating multiple spawnpoints in Unity Multiplayer
Creating multiple spawnpoints in Unity Multiplayer

Time:02-02

I'm kinda new to unity, been spinning my head around it this couple of last days. I've encoutered a problem where when I'm spawning 2 or more players into my scene they just get launched out of the map. I've figured out that it's a problem with the spawn points. I did set up a range between some values where they will be spawned but seems that they still spawn into the same spot and get lauched across the map.

What I want to do is, create 4 spawnpoints(the maximum number of people that can play the game) in which they will get spawned based on the number of players.

I have a function called "SetPosition" with the code:

    public void SetPosition()
    {
        transform.position = new Vector3(Random.Range(-1,11), 0.8f, Random.Range(-4,5));
    }

and it is used here, if the scene is "Game"

    private void Update()
    {
        if(SceneManager.GetActiveScene().name == "Game")
        {
            if(PlayerModel.activeSelf == false)
            {
                SetPosition();
                PlayerModel.SetActive(true);
            }

Any support is appreciated, been trying to find an answer but could find anything that would fit my need.

CodePudding user response:

At early stage best solution will be create 4 empty game objects at the places where you want to keep spawn point. Then take an array of Transform to store those in script and just pass the random index to get a point.

public Transform[] points;
public Vector3 GetRandomPoint()
{
    return points[Random.Range(0,point.length)].position;
}

CodePudding user response:

So I've done something. I've added 4 empty objects with a parent called "SpawnManager", also made a script for the spawn manager that is down below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
    public static SpawnManager Instance;


    Spawnpoint[] spawnpoints;


    void Awake()
    {
        Instance = this;
        spawnpoints = GetComponentsInChildren<Spawnpoint>();
    }

    public Transform GetSpawnPoint()
    {
        return spawnpoints[Random.Range(0, spawnpoints.Length)].transform;
    }
}

In the PlayerModel script where I set the spawn position for the player I've added this function but it doesn't work. No errors, but it doesn't respect the spawnpoints

    public void SetPosition()
    {
        Transform spawnpoint = SpawnManager.Instance.GetSpawnPoint();
        transform.position = spawnpoint.position;
    }

The SetPosition function was like this before I edited it:

    public void SetPosition()
    {
        transform.position = new Vector3(Random.Range(-1,11), 0.8f, Random.Range(-4,5));
    }
  • Related