public override void OnPlayerExit(Player player) { foreach (var actor in Room.actors.Where(a => a.owner == player)) { Room.NetworkDestroy(actor); } }
public override void OnPlayerExit(Player player) { //cleanup foreach (var actor in Room.actors.Where(a => a.owner == player)) { Room.NetworkDestroy(actor); } player.UserData = null; }
public override void OnPlayerEnter(Player player) { //make a new object for the player who just entered the room var playerObject = Room.NetworkInstantiate("player", Vector3.Zero, Quaternion.Identity, player); playerObject.AddComponent<PlayerComponent>(); //so we can reference the player's object easier in things like rpcs player.UserData = player; }
internal void OnFinishedInstantiate(Player player) { foreach (var c in components) { if (c.onFinishedInstantiate != null) try { c.onFinishedInstantiate(player); } catch (Exception e) { Debug.LogError(e.ToString()); } } }
internal void OnPlayerDisconnected(Player player) { foreach (var c in components) { if (c.onPlayerDisconnected != null) try { c.onPlayerDisconnected(player); } catch (Exception e) { Debug.LogError(e.ToString()); } } }
internal void OnPlayerLeftRoom(Player player) { foreach(var c in components) { if (c.onPlayerLeftRoom != null) try { c.onPlayerLeftRoom(player); } catch(Exception e){Debug.LogError(e.ToString());} } }
//This is called AFTER a connection has been approved private static void OnPlayerConnected(Player player) { //TODO: you could save where the player was last when they dc'd //then in here, move them to that room again. (if you have an mmo or something) //or move them to a lobby room //or a character select Debug.Log("player {0} connected", player.Id); player.ChangeRoom(_room.Room); }
internal void OnPlayerConnected(Player player) { foreach (var c in components) { if (c.onPlayerConnected != null) try { c.onPlayerConnected(player); } catch (Exception e) { Debug.LogError(e.Message); } } }
private void OnDeserializeStream(NetIncomingMessage netIncomingMessage, Player player) { //TODO: deserialize data from the stream if (player != netView.owner) { //Uh oh! someone is serializing data into something they don't own. //Either you coded it so that non-owners can serialize, or someone is trying to cheat. } }
public void MyTestInitialize() { _client = new TestablePNet(); _client.TestableHook.StartUpdateThread(); _client.OnRoomChange += s => _client.FinishedRoomChange(); PNetServer.OnPlayerConnected += player => player.ChangeRoom(_testRoom); _testRoom = Room.CreateRoom("test room"); _client.Connect(TestablePNet.GetTestConnectionConfig()); Thread.Sleep(250); _player = PNetServer.AllPlayers().First(f => f != null && f != Player.Server); }
internal void OnPlayerConnected(Player player) { for (int i = 0; i < components.Count; i++) { var c = components[i]; if (c.onPlayerConnected != null) try { c.onPlayerConnected(player); } catch (Exception e) { Debug.LogError(e.ToString()); } } }
private void OnDeserializeStream(NetIncomingMessage netIncomingMessage, Player player) { //deserialize data from the stream //this is run if the client serializes data. //TODO: optionally, ignore data if the StateSynchronization is Off if (player != netView.owner) { //Uh oh! someone is serializing data into something they don't own. //Either you coded it so that non-owners can serialize, or someone is trying to cheat. //ignore the value } else { //TODO: implement smoothing/lag compensation Vector3Serializer.Instance.OnDeserialize(netIncomingMessage); gameObject.Position = Vector3Serializer.Instance.Value; } }
/// <summary> /// Ran after the specified player has finished instantiating the gameobject this is attached to. /// Only gets run if this component was added before the player finishes instantiating. /// If this was added in the same game loop that the gameobject was instantiated, it will always get run. /// </summary> /// <param name="player"></param> private void OnInstantiationFinished(Player player) { if (netView.owner == player) { //The StringSerializer object implements the interface INetSerializable, //which you can of course use to make your own serialization objects to serialize pretty much anything you want //though limited by the practicality of sending large amounts of data (you shouldn't be sending images, as udp is bad idea for that) //Rpcs are reliable netView.RPC(1, player, new StringSerializer("Congratulations on spawning your first object")); } else { netView.RPC(1, player, new StringSerializer("Another player's object spawned!")); //A non-owner finished spawning the object. We might send them similar data, like what the player looks like, //but don't send them player specific data like health } //This will start state synchronization netView.StateSynchronization = NetworkStateSynchronization.Unreliable; }
/// <summary> /// send a message to the specified player /// </summary> /// <param name="rpcID"></param> /// <param name="player"></param> /// <param name="args"></param> public void RPC(byte rpcID, Player player, params INetSerializable[] args) { if (_connections.Count == 0) return; var size = 2; RPCUtils.AllocSize(ref size, args); var message = PNetServer.peer.CreateMessage(size); message.Write(viewID.guid); message.Write(rpcID); RPCUtils.WriteParams(ref message, args); PNetServer.peer.SendMessage(message, player.connection, NetDeliveryMethod.ReliableOrdered, Channels.OWNER_RPC); }
internal void SendBuffer(Player player) { foreach (var b in buffer) { var message = PNetServer.peer.CreateMessage(); b.Clone(message); Debug.Log("Sending buffered message to player " + player.Id); PNetServer.peer.SendMessage(message, player.connection, NetDeliveryMethod.ReliableOrdered, Channels.OWNER_RPC); } foreach (var b in fieldBuffer.Values) { var message = PNetServer.peer.CreateMessage(); b.Clone(message); PNetServer.peer.SendMessage(message, player.connection, NetDeliveryMethod.ReliableOrdered, Channels.SYNCHED_FIELD); } }
void DestroyOnPlayer(Player player) { player.RPC(PNet.RPCUtils.Remove, viewID); }
static void Update() { List<NetIncomingMessage> messages = new List<NetIncomingMessage>(); int counter = peer.ReadMessages(messages); foreach (var msg in messages) { //faster than switch, as most will be Data messages. if (msg.MessageType == NetIncomingMessageType.Data) { Consume(msg); peer.Recycle(msg); } else if (msg.MessageType == NetIncomingMessageType.DiscoveryRequest) { NetOutgoingMessage resp = peer.CreateMessage(); if (OnDiscoveryRequest != null) { OnDiscoveryRequest(resp); peer.SendDiscoveryResponse(resp, msg.SenderEndPoint); } } else if (msg.MessageType == NetIncomingMessageType.WarningMessage) { Debug.LogWarning(msg.ReadString()); peer.Recycle(msg); } else if (msg.MessageType == NetIncomingMessageType.ConnectionLatencyUpdated) { var latency = msg.ReadFloat(); peer.Recycle(msg); } else if (msg.MessageType == NetIncomingMessageType.ErrorMessage) { Debug.LogError(msg.ReadString()); peer.Recycle(msg); } else if (msg.MessageType == NetIncomingMessageType.ConnectionApproval) { var tag = new Player(); tag.connection = msg.SenderConnection; msg.SenderConnection.Tag = tag; if (ApproveConnection != null) { try { ApproveConnection(msg); } catch (Exception e) { msg.SenderConnection.Deny(); Debug.LogError(e.Message); } } else { msg.SenderConnection.Approve(); } peer.Recycle(msg); } else if (msg.MessageType == NetIncomingMessageType.StatusChanged) { NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte(); statusReason = msg.ReadString(); Debug.LogError("Status: {0}, {1}", status, statusReason); if (status == NetConnectionStatus.Connected) { AddPlayer(msg.SenderConnection); } else if (status == NetConnectionStatus.Disconnected) { RemovePlayer(msg.SenderConnection); } peer.Recycle(msg); } else if (msg.MessageType == NetIncomingMessageType.Error) { Debug.LogError(msg.ReadString()); //this should really never happen... peer.Recycle(msg); } else peer.Recycle(msg); } }
private void OnInstantiationFinished(Player player) { //get the player up to speed SendBuffer(player); //get all the secondary views and send them if (IsSecondaryView) return; var conn = new List<NetConnection> {player.connection}; foreach (var nview in gameObject.GetComponents<NetworkView>().Where(n => n != this)) { SendSecondaryView(nview, conn); } }
/// <summary> /// run when a player enters the room /// </summary> public virtual void OnPlayerEnter(Player player){}
/// <summary> /// Load a gameobject from a file /// </summary> /// <param name="filePath"></param> /// <param name="roomToInstantiateIn"></param> /// <param name="position"> </param> /// <param name="rotation"> </param> /// <param name="allowNetworkInstantiateIfHasNetworkView"></param> /// <param name="visibleToAll">makes all players in the room subscribed to the object</param> /// <param name="owner">owner of the loaded object if network instantiated. By default, it is the server</param> /// <returns></returns> public static GameObject Load(string filePath, Room roomToInstantiateIn, bool allowNetworkInstantiateIfHasNetworkView = false, Vector3? position = null, Quaternion? rotation = null, bool visibleToAll = true, Player owner = null) { var dser = new GameObject(); dser.Room = roomToInstantiateIn; var awakes = new List<Action>(); var config = new YamlConfig(); var actualFilePath = Path.Combine(ResourceFolder, filePath + ".prefab"); config.AddActivator<GameObject>(() => { //be returning an object we've already created, the AddComponent will work properly return dser; }); //config.AddActivator < List<ComponentTracker>>(() => //{ // return dser.components; //}); var trackers = new Stack<GameObject.ComponentTracker>(); config.AddActivator<GameObject.ComponentTracker>(() => { var ntrack = new GameObject.ComponentTracker(); trackers.Push(ntrack); return ntrack; }); foreach (Type t in GetComponentTypes()) { Type tLocal = t; if (tLocal == typeof(NetworkView) && !allowNetworkInstantiateIfHasNetworkView) { Debug.LogWarning("[Resources.Load] file {0} has a NetworkView component on it, but was run as to not network instantiate. It will not be networked.", actualFilePath); } GameObject dser1 = dser; config.AddActivator(tLocal, () => { Action awake; var ntrack = trackers.Pop(); var ret = dser1.DeserializeAddComponent(tLocal, out awake, ntrack); awakes.Add(awake); return ret; }); } var serializer = new YamlSerializer(config); serializer.DeserializeFromFile(actualFilePath, typeof(GameObject)); if (dser.Resource == null) dser.Resource = filePath; if (position.HasValue) dser.Position = position.Value; if (rotation.HasValue) dser.Rotation = rotation.Value; roomToInstantiateIn.OnGameObjectAdded(dser); foreach (var awake in awakes) if (awake != null) awake(); dser.OnComponentAfterDeserialization(); if (allowNetworkInstantiateIfHasNetworkView && dser.GetComponent<NetworkView>() != null) roomToInstantiateIn.ResourceNetworkInstantiate(dser, visibleToAll, owner); return dser; }
//This is called AFTER a connection has been approved private static void OnPlayerConnected(Player player) { //TODO: move the player to a room maybe? Debug.Log("player {0} connected", player.Id); player.ChangeRoom(_room.Room); }
void OnPlayerEnteredRoom(Player player) { if (_isVisibleToAll) { //we already have the player added to the connections list, as it was set when we set the owner. if (owner == player) return; _connections.Add(player.connection); _allButOwner.Add(player.connection); } }
public override void OnPlayerEnter(Player player) { var playerObject = NetworkInstantiate("player", Vector3.Zero, Quaternion.Identity, player); playerObject.AddComponent<PlayerComponent>(); }
/// <summary> /// Subscribe a player to this /// </summary> /// <param name="player"></param> /// <param name="isSubscribed"></param> public void SetPlayerSubscription(Player player, bool isSubscribed) { if (_isVisibleToAll) return; //the object is already visible to the specified player. if (player == owner) { Debug.LogWarning("[NetworkView.SetPlayerSubscription] Players are always subscribed to NetworkViews they own. Do not subscribe them to it."); return; } if (player.CurrentRoom != room) { Debug.LogWarning("[NetworkView.SetPlayerSubscription] Players cannot be subscribed to objects not in the same room as them."); return; } if (isSubscribed) { if (_connections.Contains(player.connection)) return; //player is already subscribed _connections.Add(player.connection); _allButOwner.Add(player.connection); room.SendNetworkInstantiate(new List<NetConnection> {player.connection}, gameObject); } else { OnPlayerLeftRoom(player); DestroyOnPlayer(player); } }
internal void SendBuffer(Player player) { for(int i = 0; i < buffer.Count; i++) { var message = PNetServer.peer.CreateMessage(); buffer[i].Clone(message); PNetServer.peer.SendMessage(message, player.connection, NetDeliveryMethod.ReliableOrdered, Channels.OWNER_RPC); } foreach (var b in fieldBuffer) { var message = PNetServer.peer.CreateMessage(); b.Value.Clone(message); PNetServer.peer.SendMessage(message, player.connection, NetDeliveryMethod.ReliableOrdered, Channels.SYNCHED_FIELD); } }
internal void OnFinishedInstantiate(Player player) { for (int i = 0; i < components.Count; i++) { var c = components[i]; if (c.onFinishedInstantiate != null) try { c.onFinishedInstantiate(player); } catch (Exception e) { Debug.LogError(e.ToString()); } } }
/// <summary> /// Set up the server, bind to a socket. Use Start to fully start the server after running this /// </summary> /// <param name="configuration"></param> public static void InitializeServer(ServerConfiguration configuration) { Configuration = configuration; if (peer != null && peer.Status != NetPeerStatus.NotRunning) { Debug.LogError("cannot start server while already running"); return; } _netPeerConfiguration = new NetPeerConfiguration(Configuration.AppIdentifier); _netPeerConfiguration.Port = Configuration.ListenPort; _netPeerConfiguration.MaximumConnections = Configuration.MaximumConnections; connections = new IntDictionary<NetConnection>(Configuration.MaximumConnections); _netPeerConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true); peer = new NetServer(_netPeerConfiguration); peer.Start(); var serverId = connections.Add(null); var serverPlayer = new Player(); serverPlayer.Id = (ushort)serverId; Player.Server = serverPlayer; GameState.update += Update; }
/// <summary> /// /// </summary> /// <param name="mode"></param> /// <param name="player"></param> internal NetMessageInfo(RPCMode mode, Player player) { this.mode = mode; this.player = player; }
/// <summary> /// run when a player exits the room /// </summary> public virtual void OnPlayerExit(Player player){}
void OnPlayerLeftRoom(Player player) { _connections.Remove(player.connection); if (player != owner) _allButOwner.Remove(player.connection); }