Example #1
0
        private void OnSetNickname(NetworkConnection conn, SetupPlayerMessage message)
        {
            clientIndex++;

            if (IsSceneActive(RoomScene))
            {
                if (roomSlots.Count == maxConnections)
                {
                    return;
                }

                allPlayersReady = false;

                GameObject  newRoomGameObject = Instantiate(roomPlayerPrefab.gameObject);
                LobbyPlayer lobbyPlayer       = newRoomGameObject.GetComponent <LobbyPlayer>();
                lobbyPlayer.playerInfo.nickname = message.nickname;

                NetworkServer.AddPlayerForConnection(conn, newRoomGameObject);
            }
            else
            {
                OnRoomServerAddPlayer(conn);
            }
        }
Example #2
0
    // Instantiate whichever character the player chose and was assigned to chosenCharacter
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        if (isWorm)
        {
            // playerPrefab = character1;
            var player1 = (GameObject)GameObject.Instantiate(character1, new Vector3(Random.Range(-15, 15), Random.Range(-9, 9), 0f), Quaternion.identity);
            NetworkServer.AddPlayerForConnection(conn, player1, playerControllerId);
            isWorm = false;
        }
        else
        {
            //playerPrefab = character2;
            var player2 = (GameObject)GameObject.Instantiate(character2, new Vector3(Random.Range(-15, 15), Random.Range(-9, 9), 0f), Quaternion.identity);
            NetworkServer.AddPlayerForConnection(conn, player2, playerControllerId);
        }


        //MsgTypes.PlayerPrefabMsg msg = new MsgTypes.PlayerPrefabMsg();
        //msg.controllerID = playerControllerId;
        //NetworkServer.SendToClient(conn.connectionId, MsgTypes.PlayerPrefab, msg);
        //MsgTypes.PlayerPrefabMsg msg = new MsgTypes.PlayerPrefabMsg();
        //msg.controllerID = playerControllerId;
        //NetworkServer.SendToClient(conn.connectionId, player1, msg);
    }
Example #3
0
        //need tow ait for the GameManager to Start(), otherwise it causes problems with the player spawning
        private IEnumerator SpawnPlayer(NetworkConnection conn, short playerControllerId)
        {
            while (GameManager.GetInstance() == null || GameManager.GetInstance().size.Count <= 0 || conn.isReady == false)
            {
                yield return(null);
            }


            int teamIndex = GameManager.GetInstance().GetTeamFill();
            //get spawn position for this team and instantiate the player there
            Vector3 startPos = GameManager.GetInstance().GetSpawnPosition(teamIndex);

            gameObject.transform.SetPositionAndRotation(startPos, Quaternion.identity);


            GameObject obj    = (GameObject)Instantiate(playerPrefab, startPos, Quaternion.identity);
            Player     player = obj.GetComponent <Player>();

            player.teamIndex = teamIndex;
            NetworkServer.AddPlayerForConnection(conn, obj, playerControllerId);

            GameManager.GetInstance().size[teamIndex]++;
            GameManager.GetInstance().Rpc_OnChangeSize();
        }
Example #4
0
        public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader)
        {
            if (TransitionParams.playerName != null)
            {
                humanPlayer = TransitionParams.playerName;
            }

            var p = Instantiate(FindPrefab(humanPlayer), Vector3.zero, Quaternion.identity);

#pragma warning disable 0219 // Unused variable
            var playerId = GameController.Instance.RegisterNewPlayer(p, "P1", TransitionParams.team, conn);
#pragma warning restore 0219
#if UNITY_EDITOR
            //StartCoroutine(SetLeaderboardIdForFacebookId(playerId));
#endif
            NetworkServer.AddPlayerForConnection(conn, p, playerControllerId);

            p = Instantiate(FindPrefab(computerPlayer), Vector3.zero, Quaternion.identity);
            p.GetComponent <NetworkIdentity>().localPlayerAuthority = false;
            GameController.Instance.RegisterNewComputerPlayer(p, "COM", -1, cpuLevel);
            NetworkServer.Spawn(p);

            GameController.Instance.StartGame();
        }
    public void createPlayer(NetworkConnection conn, short playerControllerId)
    {
        GameObject    player;
        CombatHandler combatHandler;

        /*if( numberOfPlayers%2==1 )
         * {
         *  player = (GameObject)Instantiate(playerPrefab, leftStartPoint.transform.position, Quaternion.identity);
         *  combatHandler = player.GetComponent<CombatHandler>();
         *  combatHandler.team = Team.Left;
         * }
         * else
         * {*/
        player                   = (GameObject)Instantiate(playerPrefab, rightStartPoint.transform.position, Quaternion.identity);
        combatHandler            = player.GetComponent <CombatHandler>();
        combatHandler.team       = Team.Right;
        combatHandler.spawnPoint = rightStartPoint;
        combatHandler.isPlayer   = true;
        Debug.Log("create player");
        //}
        //Debug.Log("create player");
        numberOfPlayers++;
        NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    }
Example #6
0
    /// <summary>
    /// Spawns a viewer for the specified connection and transfer the connection to this viewer.
    /// </summary>
    /// <param name="conn"></param>
    public static void ServerSpawnViewer(NetworkConnection conn)
    {
        GameObject joinedViewer = Object.Instantiate(CustomNetworkManager.Instance.playerPrefab);

        NetworkServer.AddPlayerForConnection(conn, joinedViewer, System.Guid.NewGuid());
    }
        //Control adding new Players on client connection.  Runs on the server.  Modified to respect NetworkType
        //playerControllerId is the client scoped player id, for cases where a client has more than one player (eg multiple gamepads)
        public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
        {
            GameObject player = (GameObject)Instantiate(playerPrefab, Vector3.zero, Quaternion.identity);

            NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
        }
Example #8
0
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader)
    {
        NetworkMessage message = extraMessageReader.ReadMessage <NetworkMessage>();

        //Store players in a scene in array
        GameObject[] players = GameObject.FindGameObjectsWithTag("Player");


        if (players.Length == 0)
        {
            int randCharIndex = Random.Range(0, meshes.Count);

            //Used for a ai representation
            GameObject aiPlayer = null;

            Transform spawn = NetworkManager.singleton.GetStartPosition();

            aiPlayer = Instantiate(meshes[randCharIndex], spawn.position, spawn.rotation) as GameObject;
            //				aiPlayer.GetComponent<Main> ().enabled = true;
            meshes.RemoveAt(randCharIndex);
            NetworkServer.Spawn(aiPlayer);

            //Used for a ai representation
            aiPlayer = null;

            spawn         = NetworkManager.singleton.GetStartPosition();
            randCharIndex = Random.Range(0, meshes.Count);

            aiPlayer = Instantiate(meshes[randCharIndex], spawn.position, spawn.rotation) as GameObject;
            //				aiPlayer.GetComponent<Main> ().enabled = true;
            meshes.RemoveAt(randCharIndex);
            NetworkServer.Spawn(aiPlayer);

            randCharIndex = Random.Range(0, meshes.Count);

            //Used for a ai representation
            aiPlayer = null;



            aiPlayer = Instantiate(playerDamaged, new Vector3(0, 0, 0), spawn.rotation) as GameObject;
            aiPlayer.GetComponent <DamagedBotBehavior>().enabled = true;
            //meshes.RemoveAt(randCharIndex);
            NetworkServer.Spawn(aiPlayer);

            randCharIndex = Random.Range(0, meshes.Count);

            aiPlayer = null;

            spawn = NetworkManager.singleton.GetStartPosition();

            aiPlayer = Instantiate(meshes[randCharIndex], spawn.position, spawn.rotation) as GameObject;
            aiPlayer.GetComponent <Behaviour>().enabled = true;
            meshes.RemoveAt(randCharIndex);
            NetworkServer.Spawn(aiPlayer);
        }



        if (meshes.Count != 0)
        {
            int randCharIndex = Random.Range(0, meshes.Count);

            //Used for a local player representation
            GameObject localPlayer = null;


            Transform spawn = NetworkManager.singleton.GetStartPosition();

            localPlayer = Instantiate(meshes[randCharIndex], spawn.position, spawn.rotation) as GameObject;

            meshes.RemoveAt(randCharIndex);

            NetworkServer.AddPlayerForConnection(conn, localPlayer, playerControllerId);
        }



        /*
         *      if (players.Length == 0) {
         *              Transform spawn = NetworkManager.singleton.GetStartPosition ();
         *              localPlayer = Instantiate (player, spawn.position, spawn.rotation) as GameObject;
         *
         *
         *      } else if (players.Length == 1) {
         *              Transform spawn = NetworkManager.singleton.GetStartPosition ();
         *              localPlayer = Instantiate (player, spawn.position, spawn.rotation) as GameObject;
         *
         *      } else if (players.Length == 2) {
         *              Transform spawn = NetworkManager.singleton.GetStartPosition ();
         *              localPlayer = Instantiate (player, spawn.position, spawn.rotation) as GameObject;
         *      }
         */
    }
Example #9
0
 public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
 {
     thePlayer = (GameObject)OnSpawnPlayer(Vector3.zero, playerHash);
     NetworkServer.AddPlayerForConnection(conn, thePlayer, playerControllerId, playerHash);
 }
Example #10
0
        public override GameObject OnLobbyServerCreateGamePlayer(NetworkConnection conn, short playerControllerId)
        {
            GameObject[] players = GameObject.FindGameObjectsWithTag("Player");

            GameObject localPlayer = null;

            if (players.Length == 0)
            {
                for (int i = 0; i < aiCount; i++)
                {
                    int randCharIndex = Random.Range(0, meshes.Count);

                    //Used for a ai representation
                    GameObject aiPlayer = null;

                    Transform spawn = NetworkManager.singleton.GetStartPosition();

                    aiPlayer = Instantiate(meshes[randCharIndex], spawn.position, spawn.rotation) as GameObject;
                    aiPlayer.GetComponent <AI_behaviour>().enabled        = true;
                    aiPlayer.GetComponent <AI_behaviour>().useMoralScheme = true;
                    meshes.RemoveAt(randCharIndex);

                    NetworkServer.Spawn(aiPlayer);
                }


                if (selectedScene == "PASSENGERS")
                {
                    //Damaged ai behavior
                    GameObject aiPlayer = null;
                    aiPlayer = Instantiate(playerDamaged, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
                    aiPlayer.GetComponent <DamagedBotBehavior>().enabled = true;
                    NetworkServer.Spawn(aiPlayer);
                }
            }



            if (meshes.Count != 0)
            {
                int randCharIndex = Random.Range(0, meshes.Count);


                Transform spawn = NetworkManager.singleton.GetStartPosition();

                localPlayer = Instantiate(meshes[randCharIndex], spawn.position, spawn.rotation) as GameObject;

                // Debug.Log("Created player of " + randCharIndex);

                if (realPlayers == 0)
                {
                    localPlayer.GetComponent <AI_behaviour>().enabled = true;
                }

                meshes.RemoveAt(randCharIndex);

                NetworkServer.AddPlayerForConnection(conn, localPlayer, playerControllerId);
            }


            return(localPlayer);
        }
Example #11
0
        void AddPlayer(NetworkConnection conn, short playerControllerId, PlayerSelection selection)
        {
            if (playerControllerId < conn.playerControllers.Count &&
                conn.playerControllers[playerControllerId].IsValid &&
                conn.playerControllers[playerControllerId].gameObject != null)
            {
                Log.Error("There is already a player at that playerControllerId for this connections.");
                return;
            }

            var  startPosition = GetStartPosition();
            var  character     = selection.Character;
            bool random        = character == null;

            Analytics.CustomEvent("characterSelected", new Dictionary <string, object> {
                { "character", character != null ? character.name : "Random" },
                { "color", selection.Pallete },
            });
            if (random)
            {
                Log.Info("No character was specfied, randomly selecting character and pallete...");
                selection.Character = DataManager.Characters.Random();
                selection.Pallete   = Mathf.FloorToInt(Random.value * selection.Character.PalleteCount);
            }
            var sameCharacterSelections = new HashSet <PlayerSelection>(PlayerManager.MatchPlayers.Select(p => p.Selection));

            if (sameCharacterSelections.Contains(selection))
            {
                bool success = false;
                for (var i = 0; i < selection.Character.PalleteCount; i++)
                {
                    selection.Pallete = i;
                    if (!sameCharacterSelections.Contains(selection))
                    {
                        success = true;
                        break;
                    }
                }
                if (!success)
                {
                    Log.Error("Two players made the same selection, and no remaining palletes remain. {0} doesn't have enough colors".With(selection.Character));
                    ClientScene.RemovePlayer(playerControllerId);
                    return;
                }
            }

            selection.Character.Prefab.LoadAsync().Then(prefab => {
                if (prefab == null)
                {
                    Log.Error("The character {0} does not have a prefab. Please add a prefab object to it.", selection.Character);
                    return;
                }

                if (prefab.GetComponent <NetworkIdentity>() == null)
                {
                    Log.Error(
                        "The character prefab for {0} does not have a NetworkIdentity. Please add a NetworkIdentity to it's prefab.",
                        selection.Character);
                    return;
                }

                GameObject playerObj;
                if (startPosition != null)
                {
                    playerObj = Instantiate(prefab, startPosition.position, startPosition.rotation);
                }
                else
                {
                    playerObj = Instantiate(prefab, Vector3.zero, Quaternion.identity);
                }
                var player     = PlayerManager.MatchPlayers.Get(playerCount);
                playerObj.name = "Player {0} ({1},{2})".With(playerCount + 1, selection.Character.name, selection.Pallete);
                NetworkServer.AddPlayerForConnection(conn, playerObj, playerControllerId);
                var colorState = playerObj.GetComponentInChildren <ColorState>();
                if (colorState != null)
                {
                    colorState.Pallete = selection.Pallete;
                }
                player.Selection    = selection;
                player.Type         = PlayerType.HumanPlayer;
                player.PlayerObject = playerObj;
                playerCount++;
                NetworkServer.SendToAll(Messages.UpdatePlayer, UpdatePlayerMessage.FromPlayer(player));
                var playerConnection = new PlayerConnection {
                    ConnectionID       = conn.connectionId,
                    PlayerControllerID = playerControllerId
                };
                PlayerMap[playerConnection] = player;
                playerObj.GetComponentsInChildren <IDataComponent <Player> >().SetData(player);
                //player.Changed += () => playerObj.GetComponentInChildren<IDataComponent<Player>>().SetData(player);
            });
        }
    /// <summary>
    /// Adds the player via the SQL architecture.
    /// </summary>
    /// <param name="conn">The connection.</param>
    /// <param name="playerControllerId">The player controller identifier.</param>
    /// <returns></returns>
    private IEnumerator AddPlayerSql(NetworkConnection conn, short playerControllerId)
    {
        WWW result = new WWW("http://localhost:8080/seagull/get-player-data.php");

        yield return(result);

        if (result.error != null)
        {
            Debug.LogError("Error, unable to retrieve player location!");
        }
        else
        {
            NetworkInitializer initializerScript = GetComponent <NetworkInitializer>();

            // Ideally we would use log in information to spawn the player here.
            // for now its first come first serve.
            string[] playersString = result.text.Split('|');
            string[] playerCurrent = playersString[_playersSql.Count].Split(',');

            // This represents the player data extracted from plain text html :/
            PlayerInfoSql playerData = new PlayerInfoSql(
                new Users()
            {
                user_id = Convert.ToInt32(playerCurrent[0]),
                name    = playerCurrent[1]
            },
                new PlayerLocation()
            {
                location = new Location
                {
                    x = Convert.ToSingle(playerCurrent[2]),
                    y = Convert.ToSingle(playerCurrent[3]),
                    z = Convert.ToSingle(playerCurrent[4]),
                },
                rotation = new Rotation
                {
                    x = Convert.ToSingle(playerCurrent[5]),
                    y = Convert.ToSingle(playerCurrent[6]),
                    z = Convert.ToSingle(playerCurrent[7]),
                    w = Convert.ToSingle(playerCurrent[8])
                }
            },
                playerCount, initializerScript);

            Debug.Log("Player count: " + _playersSql.Count);
            Debug.Log("Added User: "******"playerId" + playerCount);

            // Spawn the player.
            Vector3 spawnPosition = new Vector3(
                Convert.ToSingle(playerData.PlayerLocation.location.x),
                Convert.ToSingle(playerData.PlayerLocation.location.y),
                Convert.ToSingle(playerData.PlayerLocation.location.z));

            Quaternion spawRotation = new Quaternion(
                Convert.ToSingle(playerData.PlayerLocation.rotation.x),
                Convert.ToSingle(playerData.PlayerLocation.rotation.y),
                Convert.ToSingle(playerData.PlayerLocation.rotation.z),
                Convert.ToSingle(playerData.PlayerLocation.rotation.w));

            var playerObject = (GameObject)GameObject.Instantiate(playerPrefab, spawnPosition, spawRotation);

            playerData.SetPlayerObject(playerObject);

            NetworkServer.AddPlayerForConnection(conn, playerObject, playerControllerId);

            // adds the player to the game.
            _playersSql.Add(playerCount, playerData);

            Debug.Log(_playersSql[playerCount].ToString());
            playerCount++;
        }
    }
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        if (playerPrefab == null)
        {
            if (LogFilter.logError)
            {
                Debug.LogError("The PlayerPrefab is empty on the NetworkManager. Please setup a PlayerPrefab object.");
            }
            return;
        }

        if (playerPrefab.GetComponent <NetworkIdentity>() == null)
        {
            if (LogFilter.logError)
            {
                Debug.LogError("The PlayerPrefab does not have a NetworkIdentity. Please add a NetworkIdentity to the player prefab.");
            }
            return;
        }

        if (playerControllerId < conn.playerControllers.Count && conn.playerControllers[playerControllerId].IsValid && conn.playerControllers[playerControllerId].gameObject != null)
        {
            if (LogFilter.logError)
            {
                Debug.LogError("There is already a player at that playerControllerId for this connections.");
            }
            return;
        }

        GameObject player;
        Transform  startPos = GetStartPosition();

        if (startPos != null)
        {
            player = (GameObject)Instantiate(playerPrefab, startPos.position, startPos.rotation);
        }
        else
        {
            player = (GameObject)Instantiate(playerPrefab, Vector3.zero, Quaternion.identity);
        }

        player.GetComponent <PlayerController>().localConn       = conn;
        player.GetComponent <PlayerController>().initialPosition = player.transform.position;

        Client client = new Client(conn, player);

        clients.Add(client);
        players.Add(player);

        NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);

        if (clients.Count >= minPlayerCount)
        {
            Debug.Log("Start pregame");

            characterArray = GameObject.FindGameObjectsWithTag("NPC");
            foreach (GameObject character in characterArray)
            {
                characters.Add(character);
            }
            foreach (GameObject plyr in players)
            {
                characters.Add(plyr);
            }

            shuffleObjectList(characters);
            Debug.Log(characters.Count);
            giveAttributes();
            shuffleObjectList(players);
            giveTarget();

            player.GetComponent <PlayerController> ().LoadPregame();
        }
    }
Example #14
0
    //----------------------------------------------------------------------------------------------------
    /// <summary>
    /// プレイヤーを足すときのメソッド
    /// </summary>
    /// <param name="conn">クライアントから接続を開始</param>
    /// <param name="playerControllerId">プレイヤーID</param>
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        var player = Instantiate(playerPrefab, GameObject.Find("Players").transform);

        NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    }
    // On the server, we create the player object using Zenject's container.
    public override void OnServerAddPlayer(NetworkConnection connection, short playerControllerId)
    {
        GameObject player = _container.InstantiatePrefab(_settings.PlayerPrefab);

        NetworkServer.AddPlayerForConnection(connection, player, playerControllerId);
    }
Example #16
0
        public IEnumerator Setup() => RunAsync(async() =>
        {
            serverGo      = new GameObject("server", typeof(NetworkSceneManager), typeof(NetworkServer));
            clientGo      = new GameObject("client", typeof(NetworkSceneManager), typeof(NetworkClient));
            testTransport = serverGo.AddComponent <LoopbackTransport>();

            await Task.Delay(1);

            server = serverGo.GetComponent <NetworkServer>();
            client = clientGo.GetComponent <NetworkClient>();

            server.transport = testTransport;
            client.Transport = testTransport;

            serverSceneManager = serverGo.GetComponent <NetworkSceneManager>();
            clientSceneManager = clientGo.GetComponent <NetworkSceneManager>();

            serverSceneManager.server = server;
            clientSceneManager.client = client;

            ExtraSetup();

            // create and register a prefab
            playerPrefab = new GameObject("serverPlayer", typeof(NetworkIdentity), typeof(T));
            playerPrefab.GetComponent <NetworkIdentity>().AssetId = Guid.NewGuid();
            client.RegisterPrefab(playerPrefab);

            // wait for client and server to initialize themselves
            await Task.Delay(1);

            // start the server
            await server.ListenAsync();

            await Task.Delay(1);

            var builder = new UriBuilder
            {
                Host   = "localhost",
                Scheme = client.Transport.Scheme.First(),
            };

            // now start the client
            await client.ConnectAsync(builder.Uri);

            await WaitFor(() => server.connections.Count > 0);

            // get the connections so that we can spawn players
            connectionToClient = server.connections.First();
            connectionToServer = client.Connection;

            // create a player object in the server
            serverPlayerGO  = Object.Instantiate(playerPrefab);
            serverIdentity  = serverPlayerGO.GetComponent <NetworkIdentity>();
            serverComponent = serverPlayerGO.GetComponent <T>();
            server.AddPlayerForConnection(connectionToClient, serverPlayerGO);

            // wait for client to spawn it
            await WaitFor(() => connectionToServer.Identity != null);

            clientIdentity  = connectionToServer.Identity;
            clientPlayerGO  = clientIdentity.gameObject;
            clientComponent = clientPlayerGO.GetComponent <T>();
        });
Example #17
0
    public void OnCreateCharacter(NetworkConnection conn, PosMessage message)
    {
        GameObject go = Instantiate(playerPrefab, message.vector2, Quaternion.identity); //локально на сервере создаем gameObject

        NetworkServer.AddPlayerForConnection(conn, go);                                  //присоеднияем gameObject к пулу сетевых объектов и отправляем информацию об этом остальным игрокам
    }
Example #18
0
        public override void OnServerAddPlayer(NetworkConnection conn)
        {
            GameObject player = Instantiate(playerPrefab, spawnplayer[numPlayers].position, spawnplayer[numPlayers].rotation);

            NetworkServer.AddPlayerForConnection(conn, player);
        }
Example #19
0
    public override void OnRoomServerAddPlayer(NetworkConnection conn)
    {
        GameObject player = OnRoomServerCreateRoomPlayer(conn);

        NetworkServer.AddPlayerForConnection(conn, player);
    }
Example #20
0
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        //if these are still null set them again (race condition?)
        if (_team1SpawnLocations == null)
        {
            _team1SpawnLocations = _map._team1SpawnLocations;
        }

        if (_team2SpawnLocations == null)
        {
            _team2SpawnLocations = _map._team2SpawnLocations;
        }

        GameObject player;
        Unit       unit;

        //if this is the host client, spawn them on the other side of the map
        if (playerControllerId < NUM_UNITS_PER_TEAM)
        {
            //spawn leader
            if (playerControllerId == 0)
            {
                UnitSpawn leaderSpawn = _team2SpawnLocations.FirstOrDefault(s => s._unitType.Equals("leader"));
                player = Instantiate(Leader2, _map.TileCoordToWorldCoord(leaderSpawn._x, leaderSpawn._z), Quaternion.identity) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), leaderSpawn._x, leaderSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 1);
                _team1SpawnLocations.Remove(leaderSpawn);
            }
            //spawn wizard
            else if (playerControllerId == 1)
            {
                UnitSpawn wizSpawn = _team2SpawnLocations.FirstOrDefault(s => s._unitType.Equals("wizard"));
                player = Instantiate(Wizard2, _map.TileCoordToWorldCoord(wizSpawn._x, wizSpawn._z), Quaternion.identity) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), wizSpawn._x, wizSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 1);
                _team2SpawnLocations.Remove(wizSpawn);
            }
            //spawn knights
            else if (playerControllerId <= 3)
            {
                UnitSpawn knightSpawn = _team2SpawnLocations.FirstOrDefault(s => s._unitType.Equals("knight"));
                player = Instantiate(Knight2, _map.TileCoordToWorldCoord(knightSpawn._x, knightSpawn._z), Quaternion.identity) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), knightSpawn._x, knightSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 1);
                _team2SpawnLocations.Remove(knightSpawn);
            }
            //spawn spearman
            else if (playerControllerId <= 5)
            {
                UnitSpawn spearSpawn = _team2SpawnLocations.FirstOrDefault(s => s._unitType.Equals("spear"));
                player = Instantiate(Spearman2, _map.TileCoordToWorldCoord(spearSpawn._x, spearSpawn._z), Quaternion.identity) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), spearSpawn._x, spearSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 1);
                _team2SpawnLocations.Remove(spearSpawn);
            }
            //spawn warriors
            else
            {
                UnitSpawn warrSpawn = _team2SpawnLocations.FirstOrDefault(s => s._unitType.Equals("warrior"));
                player = Instantiate(Warrior2, _map.TileCoordToWorldCoord(warrSpawn._x, warrSpawn._z), Quaternion.identity) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), warrSpawn._x, warrSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 1);
                _team2SpawnLocations.Remove(warrSpawn);
            }
        }
        else
        {
            //spawn leader
            if (playerControllerId == NUM_UNITS_PER_TEAM)
            {
                UnitSpawn leaderSpawn = _team1SpawnLocations.FirstOrDefault(s => s._unitType.Equals("leader"));
                player = Instantiate(Leader1, _map.TileCoordToWorldCoord(leaderSpawn._x, leaderSpawn._z), Quaternion.Euler(0, 180, 0)) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), leaderSpawn._x, leaderSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 2);
                _team1SpawnLocations.Remove(leaderSpawn);
            }
            //spawn wizard
            else if (playerControllerId == NUM_UNITS_PER_TEAM + 1)
            {
                UnitSpawn wizSpawn = _team1SpawnLocations.FirstOrDefault(s => s._unitType.Equals("wizard"));
                player = Instantiate(Wizard1, _map.TileCoordToWorldCoord(wizSpawn._x, wizSpawn._z), Quaternion.Euler(0, 180, 0)) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), wizSpawn._x, wizSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 2);
                _team1SpawnLocations.Remove(wizSpawn);
            }
            //spawn knights
            else if (playerControllerId <= NUM_UNITS_PER_TEAM + 3)
            {
                UnitSpawn knightSpawn = _team1SpawnLocations.FirstOrDefault(s => s._unitType.Equals("knight"));
                player = Instantiate(Knight1, _map.TileCoordToWorldCoord(knightSpawn._x, knightSpawn._z), Quaternion.Euler(0, 180, 0)) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), knightSpawn._x, knightSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 2);
                _team1SpawnLocations.Remove(knightSpawn);
            }
            //spawn spearman
            else if (playerControllerId <= NUM_UNITS_PER_TEAM + 5)
            {
                UnitSpawn spearSpawn = _team1SpawnLocations.FirstOrDefault(s => s._unitType.Equals("spear"));
                player = Instantiate(Spearman1, _map.TileCoordToWorldCoord(spearSpawn._x, spearSpawn._z), Quaternion.Euler(0, 180, 0)) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), spearSpawn._x, spearSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 2);
                _team1SpawnLocations.Remove(spearSpawn);
            }
            //spawn warriors
            else
            {
                UnitSpawn warrSpawn = _team1SpawnLocations.FirstOrDefault(s => s._unitType.Equals("warrior"));
                player = Instantiate(Warrior1, _map.TileCoordToWorldCoord(warrSpawn._x, warrSpawn._z), Quaternion.Euler(0, 180, 0)) as GameObject;
                unit   = CreateUnit(player.GetComponent <Unit>(), warrSpawn._x, warrSpawn._z);
                UpdateCharacterStatus(player.GetComponent <CharacterStatus>(), 2);
                _team1SpawnLocations.Remove(warrSpawn);
            }
        }

        _units.Add(unit);

        NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    }
Example #21
0
    public static void SpawnViewer(NetworkConnection conn, short playerControllerId, JobType jobType = JobType.NULL)
    {
        GameObject joinedViewer = Object.Instantiate(networkManager.playerPrefab);

        NetworkServer.AddPlayerForConnection(conn, joinedViewer, 0);
    }
Example #22
0
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        var player = Instantiate(Utils.PopRandomFromList <GameObject>(playerPrefabs));

        NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    }
Example #23
0
 public override void OnClientConnect(NetworkConnection connection)
 {
     base.OnClientConnect(connection);
     NetworkServer.AddPlayerForConnection(connection, gamePlayerPrefab, connection.playerControllers[0].playerControllerId);
 }
Example #24
0
    private void Update()
    {
        if (this.isServer)
        {
            switch (this.currentState)
            {
            case State.WaitingForPlayers:
                this.numPlayers = this.NumConnectedPlayers;
                if (this.numPlayers == 3)
                {
                    this.EnterState(State.Countdown);
                    return;
                }
                break;

            case State.Countdown:
            {
                if (this.NumConnectedPlayers < 3)
                {
                    this.EnterState(State.WaitingForPlayers);
                    return;
                }

                this.countdownTimer -= Time.deltaTime;
                if (this.countdownTimer <= 0.0f)
                {
                    this.EnterState(State.InGame);
                    return;
                }
            }
            break;

            case State.InGame:
            {
                this.gameTimer -= Time.deltaTime;
                if (this.gameTimer <= 0.0f)
                {
                    List <GameObject> toDelete = new List <GameObject>();

                    foreach (NetworkConnection networkConnection in this.AllConnections)
                    {
                        foreach (PlayerController controller in networkConnection.playerControllers)
                        {
                            toDelete.Add(controller.gameObject);
                        }
                    }

                    if (this.pizza != null)
                    {
                        toDelete.Add(this.pizza);
                    }

                    foreach (GameObject go in toDelete)
                    {
                        NetworkServer.Destroy(go);
                    }

                    this.EnterState(State.EndOfGame);
                    return;
                }

                this.respawnRequests.Sort(delegate(RespawnRequest a, RespawnRequest b)
                    {
                        return(a.time.CompareTo(b.time));
                    });
                while (this.respawnRequests.Count > 0 && this.respawnRequests[0].time <= Time.time)
                {
                    if (this.respawnRequests[0].networkConnection != null)
                    {
                        GameObject player = Instantiate(NetworkManager.singleton.playerPrefab) as GameObject;
                        player.transform.position = NetworkManager.singleton.startPositions[UnityEngine.Random.Range(0, NetworkManager.singleton.startPositions.Count)].position;
                        player.GetComponent <PlayerMP>().synchedPlayerNum = GetPlayerNum(this.respawnRequests[0].networkConnection);
                        NetworkServer.AddPlayerForConnection(this.respawnRequests[0].networkConnection, player, 0);
                    }
                    else
                    {
                        if (this.pizza != null)
                        {
                            NetworkServer.Destroy(this.pizza);
                        }
                        this.pizza = Instantiate(this.pizzaPrefab);
                        this.pizza.transform.position = GameObject.Find("pizza_spawn").transform.position;
                        NetworkServer.Spawn(this.pizza);
                    }

                    this.respawnRequests.RemoveAt(0);
                }

                this.currentPizzaPosition = new Vector3(-50, -50, -50);
                if (this.playerWhoHasPizza != null && this.playerWhoHasPizza.playerControllers.Count > 0)
                {
                    this.currentPizzaPosition = this.playerWhoHasPizza.playerControllers[0].gameObject.transform.position;
                }
            }
            break;

            case State.EndOfGame:
            {
                this.endOfGameTimer -= Time.deltaTime;
                if (this.endOfGameTimer <= 0.0f)
                {
                    this.EnterState(State.WaitingForPlayers);
                }
            }
            break;
            }
        }
    }
Example #25
0
    public virtual void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        var player = (GameObject)GameObject.Instantiate(netMan.playerPrefab, Vector3.zero, Quaternion.identity);

        NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    }
 public void Spawn()
 {
     NetworkServer.AddPlayerForConnection(pl.GetComponent <Player>().connectionToClient, pl, 1);
 }
        public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
        {
            string loadedSceneName = SceneManager.GetSceneAt(0).name;

            if (!lobbyScenes.Contains(loadedSceneName))
            {
                return;
            }

            // check MaxPlayersPerConnection
            int numPlayersForConnection = 0;

            for (int i = 0; i < conn.playerControllers.Count; i++)
            {
                if (conn.playerControllers[i].IsValid)
                {
                    numPlayersForConnection += 1;
                }
            }

            if (numPlayersForConnection >= maxPlayersPerConnection)
            {
                if (LogFilter.logWarn)
                {
                    Debug.LogWarning("NetworkLobbyManager no more players for this connection.");
                }

                var errorMsg = new EmptyMessage();
                conn.Send(MsgType.LobbyAddPlayerFailed, errorMsg);
                return;
            }

            byte slot = FindSlot();

            if (slot == Byte.MaxValue)
            {
                if (LogFilter.logWarn)
                {
                    Debug.LogWarning("NetworkLobbyManager no space for more players");
                }

                var errorMsg = new EmptyMessage();
                conn.Send(MsgType.LobbyAddPlayerFailed, errorMsg);
                return;
            }

            var newLobbyGameObject = OnLobbyServerCreateLobbyPlayer(conn, playerControllerId);

            if (newLobbyGameObject == null)
            {
                newLobbyGameObject = (GameObject)Instantiate(lobbyPlayerPrefab.gameObject, Vector3.zero, Quaternion.identity);
            }

            var newLobbyPlayer = newLobbyGameObject.GetComponent <NetworkLobbyPlayer>();

            newLobbyPlayer.serverId = conn.connectionId;
            newLobbyPlayer.slot     = slot;
            lobbySlots[slot]        = newLobbyPlayer;
            newLobbyPlayer.colour   = _colourPool.getColour();
            newLobbyPlayer.nickname = "unknown";

            NetworkServer.AddPlayerForConnection(conn, newLobbyGameObject, playerControllerId);
        }
Example #28
0
 static public bool AddPlayerForConnection(NetworkConnection conn, GameObject player)
 {
     return(NetworkServer.AddPlayerForConnection(conn, player));
 }
    public void SpawnPlayer(NetworkConnection conn)                   // spawn a new player for the desired connection
    {
        GameObject playerObj = GameObject.Instantiate(_playerPrefab); // instantiate on server side

        NetworkServer.AddPlayerForConnection(conn, playerObj, 0);     // spawn on the clients and set owner
    }
    public void OnCreatePlayer(NetworkConnection conn, CreateTicTacToePlayerMessage message)
    {
        GameObject gameobject = Instantiate(playerPrefab, GameObject.FindGameObjectWithTag("Player Container").transform, false);

        NetworkServer.AddPlayerForConnection(conn, gameobject);
    }