/// <summary> /// Registers a handler for a message, if another handler is already registered it will log an error. /// </summary> /// <param name="msgType">Type of the <see cref="ITinyNetMessage"/>.</param> /// <param name="handler">The delegate.</param> internal void RegisterHandlerSafe(ushort msgType, TinyNetMessageDelegate handler) { if (handler == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RegisterHandlerSafe id:" + msgType + " handler is null"); } return; } if (TinyNetLogLevel.logDebug) { TinyLogger.Log("RegisterHandlerSafe id:" + msgType + " handler:" + handler.Method.Name); } if (_msgHandlers.ContainsKey(msgType)) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RegisterHandlerSafe id:" + msgType + " handler:" + handler.Method.Name + " conflict"); } return; } _msgHandlers.Add(msgType, handler); }
/// <summary> /// Caches the <see cref="ITinyNetComponent"/> /// </summary> void CacheTinyNetObjects() { if (_tinyNetComponents == null) { _tinyNetComponents = GetComponentsInChildren <ITinyNetComponent>(true); } if (_tinyNetComponents.Length <= 8) { _dirtyFlag = new BitArray(8); } else if (_tinyNetComponents.Length <= 16) { _dirtyFlag = new BitArray(16); } else if (_tinyNetComponents.Length <= 32) { _dirtyFlag = new BitArray(32); } else if (_tinyNetComponents.Length <= 64) { _dirtyFlag = new BitArray(64); } else { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyNetIdentity::CacheTinyNetObjects amount of ITinyNetComponents is bigger than 64."); } return; } }
protected virtual void CreateDirtyFlag() { int numberOfSyncVars = TinyNetStateSyncer.GetNumberOfSyncedProperties(GetType()); if (numberOfSyncVars == 0) { _dirtyFlag = null; } else if (numberOfSyncVars <= 8) { _dirtyFlag = new BitArray(8); } else if (numberOfSyncVars <= 16) { _dirtyFlag = new BitArray(16); } else if (numberOfSyncVars <= 32) { _dirtyFlag = new BitArray(32); } else if (numberOfSyncVars <= 64) { _dirtyFlag = new BitArray(64); } else { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyNetBehaviour::OnNetworkCreate amount of TinyNetSyncVar is bigger than 64."); } return; } }
/// <summary> /// Registers a handler for a message, it will not check for conflicts, but cannot be used for system messages. /// </summary> /// <param name="msgType">Type of the <see cref="ITinyNetMessage"/>.</param> /// <param name="handler">The delegate.</param> public void RegisterHandler(ushort msgType, TinyNetMessageDelegate handler) { if (handler == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RegisterHandler id:" + msgType + " handler is null"); } return; } if (msgType <= TinyNetMsgType.InternalHighest) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RegisterHandler: Cannot replace system message handler " + msgType); } return; } if (_msgHandlers.ContainsKey(msgType)) { if (TinyNetLogLevel.logDebug) { TinyLogger.Log("RegisterHandler replacing " + msgType); } _msgHandlers.Remove(msgType); } if (TinyNetLogLevel.logDebug) { TinyLogger.Log("RegisterHandler id:" + msgType + " handler:" + handler.Method.Name); } _msgHandlers.Add(msgType, handler); }
/// <summary> /// Orders the client to change to the given scene. /// </summary> /// <param name="newSceneName">Name of the new scene.</param> /// <param name="forceReload">if set to <c>true</c>, force reload.</param> public virtual void ClientChangeScene(string newSceneName, bool forceReload) { if (string.IsNullOrEmpty(newSceneName)) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("ClientChangeScene empty scene name"); } return; } if (TinyNetLogLevel.logDebug) { TinyLogger.Log("ClientChangeScene newSceneName:" + newSceneName + " networkSceneName:" + networkSceneName); } if (newSceneName == networkSceneName) { if (!forceReload) { FinishLoadScene(); return; } } s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); networkSceneName = newSceneName; }
/// <summary> /// Orders the server to change to the given scene. /// </summary> /// <param name="newSceneName">The name of the scene to change to.</param> public virtual void ServerChangeScene(string newSceneName) { if (string.IsNullOrEmpty(newSceneName)) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("ServerChangeScene empty scene name"); } return; } if (TinyNetLogLevel.logDebug) { TinyLogger.Log("ServerChangeScene " + newSceneName); } serverManager.SetAllClientsNotReady(); networkSceneName = newSceneName; s_LoadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); TinyNetStringMessage msg = new TinyNetStringMessage(networkSceneName); msg.msgType = TinyNetMsgType.Scene; serverManager.SendMessageByChannelToAllConnections(msg, DeliveryMethod.ReliableOrdered); }
//=== /// <summary> /// Readies this instance. /// </summary> /// <returns></returns> public virtual bool Ready() { if (!isConnected) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyNetClient::Ready() called but we are not connected to anything."); } return(false); } // The first connection should always be to the host. //TinyNetConnection conn = _tinyNetConns[0]; if (connToHost.isReady) { //if (TinyNetLogLevel.logError) { TinyLogger.LogError("A connection has already been set as ready. There can only be one."); } return(false); } if (TinyNetLogLevel.logDebug) { TinyLogger.Log("TinyNetClient::Ready() called with connection [" + connToHost + "]"); } var msg = new TinyNetReadyMessage(); SendMessageByChannelToTargetConnection(msg, DeliveryMethod.ReliableOrdered, connToHost); connToHost.isReady = true; TinyNetGameManager.instance.OnClientReady(); return(true); }
/// <summary> /// Network error (on send or receive) /// </summary> /// <param name="endPoint">From endPoint (can be null)</param> /// <param name="socketErrorCode">Socket error code</param> public virtual void OnNetworkError(NetEndPoint endPoint, int socketErrorCode) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("[" + TYPE + "] error " + socketErrorCode + " at: " + endPoint); } }
/// <summary> /// Called when an object is spawned on the client. /// </summary> public void OnStartClient() { if (bStartClientTwiceTest) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("OnStartClient CALLED TWICE FOR: " + gameObject + " netId:" + NetworkID + " localPlayerAuthority: " + _localPlayerAuthority); } } else { bStartClientTwiceTest = true; } for (int i = 0; i < _tinyNetObjects.Length; i++) { if (!isServer) { TinyNetScene.AddTinyNetObjectToList(_tinyNetObjects[i]); } _tinyNetObjects[i].OnStartClient(); } if (TinyNetLogLevel.logDev) { TinyLogger.Log("OnStartClient " + gameObject + " netId:" + NetworkID + " localPlayerAuthority: " + _localPlayerAuthority); } }
/// <summary> /// Called when an object is spawned on the client. /// <para> Called on the client when the object is spawned. Called after variables are synced. (Order: 2) </para> /// </summary> public void OnStartClient() { if (bStartClientTwiceTest) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("OnStartClient CALLED TWICE FOR: " + gameObject + " netId:" + TinyInstanceID + " localPlayerAuthority: " + _localPlayerAuthority); } } else { bStartClientTwiceTest = true; } { // Calling OnStartClient on those who registered LinkedList <System.Action> handlers; if (!_registeredEventHandlers.TryGetValue(TinyNetComponentEvents.OnStartClient, out handlers)) { return; } for (LinkedListNode <System.Action> currentNode = handlers.First; currentNode != null; currentNode = currentNode.Next) { currentNode.Value(); } } if (TinyNetLogLevel.logDev) { TinyLogger.Log("OnStartClient " + gameObject + " netId:" + TinyInstanceID + " localPlayerAuthority: " + _localPlayerAuthority); } }
public static void OnPostProcessScene() { int nextSceneId = 1; TinyNetIdentity[] tnis = MonoBehaviour.FindObjectsOfType <TinyNetIdentity>(); for (int i = 0; i < tnis.Length; i++) { // if we had a [ConflictComponent] attribute that would be better than this check. // also there is no context about which scene this is in. if (tnis[i].GetComponent <TinyNetGameManager>() != null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyNetGameManager has a TinyNetIdentity component. This will cause the TinyNetGameManager object to be disabled, so it is not recommended."); } } if (tnis[i].isClient || tnis[i].isServer) { continue; } tnis[i].gameObject.SetActive(false); tnis[i].ForceSceneId(nextSceneId++); } }
/// <summary> /// [Server only] Assigns the client authority. /// </summary> /// <param name="conn">The connection.</param> /// <returns><c>false</c> on error, true otherwise.</returns> public bool AssignClientAuthority(TinyNetConnection conn) { if (!isServer) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("AssignClientAuthority can only be call on the server for spawned objects."); } return(false); } if (!_localPlayerAuthority) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("AssignClientAuthority can only be used for NetworkIdentity component with LocalPlayerAuthority set."); } return(false); } if (_connectionToOwnerClient != null && conn != _connectionToOwnerClient) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("AssignClientAuthority for " + gameObject + " already has an owner. Use RemoveClientAuthority() first."); } return(false); } if (conn == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("AssignClientAuthority for " + gameObject + " owner cannot be null. Use RemoveClientAuthority() instead."); } return(false); } _connectionToOwnerClient = conn; _connectionToOwnerClient.AddOwnedObject(this); // server no longer has authority (this is called on server). Note that local client could re-acquire authority below ForceAuthority(false); OnGiveAuthority(); // send msg to that client var msg = new TinyNetClientAuthorityMessage(); msg.networkID = TinyInstanceID.NetworkID; msg.authority = true; TinyNetServer.instance.SendMessageByChannelToTargetConnection(msg, LiteNetLib.DeliveryMethod.ReliableOrdered, conn); //Saishy: Still don't have an authority callback /*if (clientAuthorityCallback != null) { * clientAuthorityCallback(conn, this, true); * }*/ return(true); }
/// <summary> /// Called when an object is spawned on the server. /// </summary> /// <param name="allowNonZeroNetId">If the object already have a NetworkId, it was probably recycled.</param> public void OnStartServer(bool allowNonZeroNetId) { if (_localPlayerAuthority) { // local player on server has NO authority _hasAuthority = false; } else { // enemy on server has authority _hasAuthority = true; } // If the instance/net ID is invalid here then this is an object instantiated from a prefab and the server should assign a valid ID if (NetworkID == 0) { NetworkID = TinyNetGameManager.instance.NextNetworkID; for (int i = 0; i < _tinyNetObjects.Length; i++) { _tinyNetObjects[i].ReceiveNetworkID(TinyNetGameManager.instance.NextNetworkID); } } else { if (allowNonZeroNetId) { //allowed } else { if (TinyNetLogLevel.logError) { TinyLogger.LogError("Object has non-zero netId " + NetworkID + " for " + gameObject); } return; } } for (int i = 0; i < _tinyNetObjects.Length; i++) { TinyNetScene.AddTinyNetObjectToList(_tinyNetObjects[i]); _tinyNetObjects[i].OnStartServer(); } if (TinyNetLogLevel.logDev) { TinyLogger.Log("OnStartServer " + gameObject + " netId:" + NetworkID); } if (_hasAuthority) { OnStartAuthority(); } }
/// <summary> /// [Server only] Removes the client authority. /// </summary> /// <param name="conn">The connection.</param> /// <returns><c>false</c> on error, true otherwise.</returns> public bool RemoveClientAuthority(TinyNetConnection conn) { if (!isServer) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RemoveClientAuthority can only be called on the server for spawned objects."); } return(false); } if (_connectionToOwnerClient == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RemoveClientAuthority for " + gameObject + " has no clientAuthority owner."); } return(false); } if (_connectionToOwnerClient != conn) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RemoveClientAuthority for " + gameObject + " has different owner."); } return(false); } _connectionToOwnerClient.RemoveOwnedObject(this); _connectionToOwnerClient = null; // server now has authority (this is only called on server) ForceAuthority(true); OnRemoveAuthority(); // send msg to that client var msg = new TinyNetClientAuthorityMessage(); msg.networkID = TinyInstanceID.NetworkID; msg.authority = false; TinyNetServer.instance.SendMessageByChannelToTargetConnection(msg, LiteNetLib.DeliveryMethod.ReliableOrdered, conn); //Saishy: Still don't have an authority callback /*if (clientAuthorityCallback != null) { * clientAuthorityCallback(conn, this, false); * }*/ return(true); }
//Authority? // happens on client /// <summary> /// [Client only] Handles the client authority. /// </summary> /// <param name="authority">if set to <c>rue</c> [authority].</param> internal void HandleClientAuthority(bool authority) { if (!_localPlayerAuthority) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("HandleClientAuthority " + gameObject + " does not have localPlayerAuthority"); } return; } ForceAuthority(authority); }
/// <summary> /// Requests a new <see cref="TinyNetPlayerController"/> to the server. /// </summary> /// <param name="amountPlayers">The amount of players to create.</param> public void RequestAddPlayerControllerToServer(int amountPlayers = 1) { if (amountPlayers <= 0) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RequestAddPlayerControllerToServer() called with amountPlayers <= 0"); } return; } s_TinyNetRequestAddPlayerMessage.amountOfPlayers = (ushort)amountPlayers; SendMessageByChannelToTargetConnection(s_TinyNetRequestAddPlayerMessage, DeliveryMethod.ReliableOrdered, connToHost); }
/// <inheritdoc /> public virtual bool InvokeRPC(int rpcMethodIndex, NetDataReader reader) { if (rpcHandlers[rpcMethodIndex] == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyNetBehaviour::InvokeRPC netId:" + NetworkID + " RPCDelegate is not registered."); } return(false); } rpcHandlers[rpcMethodIndex].Invoke(reader); return(true); }
static bool GetTinyNetIdentity(GameObject go, out TinyNetIdentity view) { view = go.GetComponent <TinyNetIdentity>(); if (view == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyBirdNet failure. GameObject doesn't have TinyNetIdentity."); } return(false); } return(true); }
/// <summary> /// Spawns the object. /// </summary> /// <param name="obj">The object to spawn.</param> public void SpawnObject(GameObject obj) { if (!isRunning) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("SpawnObject for " + obj + ", NetworkServer is not active. Cannot spawn objects without an active server."); } return; } TinyNetIdentity objTinyNetIdentity; if (!GetTinyNetIdentity(obj, out objTinyNetIdentity)) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("SpawnObject " + obj + " has no TinyNetIdentity. Please add a TinyNetIdentity to " + obj); } return; } objTinyNetIdentity.OnNetworkCreate(); objTinyNetIdentity.OnStartServer(false); AddTinyNetIdentityToList(objTinyNetIdentity); if (TinyNetLogLevel.logDebug) { TinyLogger.Log("SpawnObject instance ID " + objTinyNetIdentity.NetworkID + " asset GUID " + objTinyNetIdentity.assetGUID); } //objTinyNetIdentity.RebuildObservers(true); //SendSpawnMessage(objTinyNetIdentity, null); // Using ShowObjectToConnection prevents the server from sending spawn messages of objects that are already spawned. for (int i = 0; i < tinyNetConns.Count; i++) { tinyNetConns[i].ShowObjectToConnection(objTinyNetIdentity); } /*foreach (TinyNetConnection conn in tinyNetConns) { * conn.ShowObjectToConnection(objTinyNetIdentity); * }*/ }
//============ TinyNetMessages Handlers =============// /// <summary> /// Called when an RPC message is received. /// </summary> /// <param name="netMsg">The net message.</param> protected virtual void OnRPCMessage(TinyNetMessageReader netMsg) { netMsg.ReadMessage(s_TinyNetRPCMessage); ITinyNetObject iObj = GetTinyNetObjectByNetworkID(s_TinyNetRPCMessage.networkID); if (iObj == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyNetScene::OnRPCMessage No ITinyNetObject with the HNetworkID: " + s_TinyNetRPCMessage.networkID); } return; } recycleMessageReader.reader.SetSource(s_TinyNetRPCMessage.parameters); iObj.InvokeRPC(s_TinyNetRPCMessage.rpcMethodIndex, recycleMessageReader.reader); }
public static void AddPropertyToType(PropertyInfo prop, Type type) { MethodInfo getMethod = prop.GetGetMethod(true); MethodInfo setMethod = prop.GetSetMethod(true); if (getMethod != null && setMethod != null) { syncVarProps[type].Add(prop); } else { if (TinyNetLogLevel.logError) { TinyLogger.LogError("TinyNetSyncVar used on property without get and/or set: " + prop.Name); } return; } }
/// <summary> /// Registers a spawn handler. /// </summary> /// <param name="assetIndex">Id of the asset.</param> /// <param name="spawnHandler">The spawn handler.</param> /// <param name="unspawnHandler">The unspawn handler.</param> public void RegisterSpawnHandler(int assetIndex, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) { if (spawnHandler == null || unspawnHandler == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("RegisterSpawnHandler custom spawn function null for " + assetIndex); } return; } if (TinyNetLogLevel.logDebug) { TinyLogger.Log("RegisterSpawnHandler asset '" + assetIndex + "' " + spawnHandler.Method.Name + "/" + unspawnHandler.Method.Name); } _spawnHandlers[assetIndex] = spawnHandler; _unspawnHandlers[assetIndex] = unspawnHandler; }
/// <summary> /// Called when a <see cref="TinyNetRequestRemovePlayerMessage"/> is received. /// </summary> /// <param name="netMsg">The net message.</param> void OnRequestRemovePlayerMessage(TinyNetMessageReader netMsg) { netMsg.ReadMessage(s_TinyNetRequestRemovePlayerMessage); if (s_TinyNetRequestRemovePlayerMessage.playerControllerId <= 0) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("OnRequestRemovePlayerMessage() called with playerControllerId <= 0"); } return; } RemovePlayerControllerFromConnection(netMsg.tinyNetConn, s_TinyNetRequestRemovePlayerMessage.playerControllerId); // Tell the origin client to remove them too! s_TinyNetRemovePlayerMessage.playerControllerId = s_TinyNetRequestRemovePlayerMessage.playerControllerId; SendMessageByChannelToTargetConnection(s_TinyNetRemovePlayerMessage, DeliveryMethod.ReliableOrdered, netMsg.tinyNetConn); }
//============ Players Methods ======================// /// <summary> /// Attempts to add a player controller to the connection. /// </summary> /// <param name="conn">The connection.</param> /// <param name="playerControllerId">The player controller identifier.</param> protected virtual void AddPlayerControllerToConnection(TinyNetConnection conn, int playerControllerId) { if (playerControllerId < 0) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("AddPlayerControllerToConnection() called with playerControllerId < 0"); } return; } if (playerControllerId < conn.playerControllers.Count && conn.playerControllers[playerControllerId].IsValid) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("There is already a player with that playerControllerId for this connection"); } return; } CreatePlayerAndAdd(conn, playerControllerId); }
/// <summary> /// Starts the client. /// </summary> /// <returns></returns> public virtual bool StartClient() { if (_netManager != null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("[" + TYPE + "] StartClient() called multiple times."); } return(false); } _netManager = new NetManager(this); _netManager.Start(); ConfigureNetManager(true); if (TinyNetLogLevel.logDev) { TinyLogger.Log("[" + TYPE + "] Started client"); } return(true); }
/// <summary> /// Called when a <see cref="TinyNetRequestAddPlayerMessage"/> is received. /// </summary> /// <param name="netMsg">The net message.</param> void OnRequestAddPlayerMessage(TinyNetMessageReader netMsg) { netMsg.ReadMessage(s_TinyNetRequestAddPlayerMessage); if (s_TinyNetRequestAddPlayerMessage.amountOfPlayers <= 0) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("OnRequestAddPlayerMessage() called with amountOfPlayers <= 0"); } return; } // Check here if you should create another player controller for that connection. int playerId = TinyNetGameManager.instance.NextPlayerID; //netMsg.tinyNetConn.playerControllers.Count; AddPlayerControllerToConnection(netMsg.tinyNetConn, playerId); // Tell the origin client to add them too! s_TinyNetAddPlayerMessage.playerControllerId = (short)playerId; SendMessageByChannelToTargetConnection(s_TinyNetAddPlayerMessage, DeliveryMethod.ReliableOrdered, netMsg.tinyNetConn); }
/// <summary> /// Starts the server. /// </summary> /// <param name="port">The port.</param> /// <param name="maxNumberOfPlayers">The maximum number of players.</param> /// <returns></returns> public virtual bool StartServer(int port, int maxNumberOfPlayers) { if (_netManager != null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("[" + TYPE + "] StartServer() called multiple times."); } return(false); } _netManager = new NetManager(this); _netManager.Start(port); ConfigureNetManager(true); if (TinyNetLogLevel.logDev) { TinyLogger.Log("[" + TYPE + "] Started server at port: " + port + " with maxNumberOfPlayers: " + maxNumberOfPlayers); } return(true); }
/// <summary> /// Called when a scene object is spawned. /// </summary> /// <param name="netMsg">A wrapper for a <see cref="TinyNetObjectSpawnSceneMessage"/>.</param> void OnObjectSpawnScene(TinyNetMessageReader netMsg) { netMsg.ReadMessage(s_TinyNetObjectSpawnSceneMessage); if (TinyNetLogLevel.logDebug) { TinyLogger.Log("Client spawn scene handler instantiating [networkID: " + s_TinyNetObjectSpawnSceneMessage.networkID + " sceneId: " + s_TinyNetObjectSpawnSceneMessage.sceneId + " pos: " + s_TinyNetObjectSpawnSceneMessage.position); } TinyNetIdentity localTinyNetIdentity = GetTinyNetIdentityByNetworkID(s_TinyNetObjectSpawnSceneMessage.networkID); if (localTinyNetIdentity != null) { // this object already exists (was in the scene) ApplyInitialState(localTinyNetIdentity, s_TinyNetObjectSpawnSceneMessage.position, s_TinyNetObjectSpawnSceneMessage.initialState, s_TinyNetObjectSpawnSceneMessage.networkID, localTinyNetIdentity.gameObject, s_TinyNetObjectSpawnSceneMessage.frameTick); return; } TinyNetIdentity spawnedId = SpawnSceneObject(s_TinyNetObjectSpawnSceneMessage.sceneId); if (spawnedId == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("Spawn scene object not found for " + s_TinyNetObjectSpawnSceneMessage.sceneId); } return; } if (TinyNetLogLevel.logDebug) { TinyLogger.Log("Client spawn for [networkID :" + s_TinyNetObjectSpawnSceneMessage.networkID + "] [sceneId: " + s_TinyNetObjectSpawnSceneMessage.sceneId + "] obj: " + spawnedId.gameObject.name); } ApplyInitialState(spawnedId, s_TinyNetObjectSpawnSceneMessage.position, s_TinyNetObjectSpawnSceneMessage.initialState, s_TinyNetObjectSpawnSceneMessage.networkID, spawnedId.gameObject, s_TinyNetObjectSpawnSceneMessage.frameTick); }
/// <summary> /// Removes the player controller from this connection. /// </summary> /// <param name="playerControllerId">The player controller identifier.</param> public void RemovePlayerController(short playerControllerId) { /*int count = _playerControllers.Count; * * while (count >= 0) { * if (playerControllerId == count && playerControllerId == _playerControllers[count].playerControllerId) { * _playerControllers[count] = new TinyNetPlayerController(); * return; * } * count -= 1; * }*/ TinyNetPlayerController tPC; if (GetPlayerController(playerControllerId, out tPC)) { _playerControllers.Remove(tPC); return; } if (TinyNetLogLevel.logError) { TinyLogger.LogError("RemovePlayerController for playerControllerId " + playerControllerId + " not found"); } }
/// <summary> /// Called when an object is spawned. /// </summary> /// <param name="netMsg">A wrapper for a <see cref="TinyNetObjectSpawnMessage"/>.</param> void OnObjectSpawn(TinyNetMessageReader netMsg) { netMsg.ReadMessage(s_TinyNetObjectSpawnMessage); if (s_TinyNetObjectSpawnMessage.assetIndex < 0 || s_TinyNetObjectSpawnMessage.assetIndex > int.MaxValue || s_TinyNetObjectSpawnMessage.assetIndex > TinyNetGameManager.instance.GetAmountOfRegisteredAssets()) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("OnObjSpawn networkID: " + s_TinyNetObjectSpawnMessage.networkID + " has invalid asset Id"); } return; } if (TinyNetLogLevel.logDev) { TinyLogger.Log("Client spawn handler instantiating [networkID:" + s_TinyNetObjectSpawnMessage.networkID + " asset ID:" + s_TinyNetObjectSpawnMessage.assetIndex + " pos:" + s_TinyNetObjectSpawnMessage.position + "]"); } TinyNetIdentity localTinyNetIdentity = GetTinyNetIdentityByNetworkID(s_TinyNetObjectSpawnMessage.networkID); // Check if this object was already registered in the scene: if (localTinyNetIdentity != null) { // this object already exists (was in the scene), just apply the update to existing object. ApplyInitialState(localTinyNetIdentity, s_TinyNetObjectSpawnMessage.position, s_TinyNetObjectSpawnMessage.initialState, s_TinyNetObjectSpawnMessage.networkID, null, s_TinyNetObjectSpawnMessage.frameTick); return; } GameObject prefab; SpawnDelegate handler; prefab = TinyNetGameManager.instance.GetPrefabFromAssetId(s_TinyNetObjectSpawnMessage.assetIndex); // Check if the prefab is registered in the list of spawnable prefabs. if (prefab != null) { var obj = (GameObject)Object.Instantiate(prefab, s_TinyNetObjectSpawnMessage.position, Quaternion.identity); localTinyNetIdentity = obj.GetComponent <TinyNetIdentity>(); if (localTinyNetIdentity == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("Client object spawned for " + s_TinyNetObjectSpawnMessage.assetIndex + " does not have a TinyNetidentity"); } return; } ApplyInitialState(localTinyNetIdentity, s_TinyNetObjectSpawnMessage.position, s_TinyNetObjectSpawnMessage.initialState, s_TinyNetObjectSpawnMessage.networkID, obj, s_TinyNetObjectSpawnMessage.frameTick); // If not, check if the prefab have a spawn handler registered. } else if (TinyNetGameManager.instance.GetSpawnHandler(s_TinyNetObjectSpawnMessage.assetIndex, out handler)) { GameObject obj = handler(s_TinyNetObjectSpawnMessage.position, s_TinyNetObjectSpawnMessage.assetIndex); if (obj == null) { if (TinyNetLogLevel.logWarn) { TinyLogger.LogWarning("Client spawn handler for " + s_TinyNetObjectSpawnMessage.assetIndex + " returned null"); } return; } localTinyNetIdentity = obj.GetComponent <TinyNetIdentity>(); if (localTinyNetIdentity == null) { if (TinyNetLogLevel.logError) { TinyLogger.LogError("Client object spawned for " + s_TinyNetObjectSpawnMessage.assetIndex + " does not have a network identity"); } return; } localTinyNetIdentity.SetDynamicAssetGUID(TinyNetGameManager.instance.GetAssetGUIDFromAssetId(s_TinyNetObjectSpawnMessage.assetIndex)); ApplyInitialState(localTinyNetIdentity, s_TinyNetObjectSpawnMessage.position, s_TinyNetObjectSpawnMessage.initialState, s_TinyNetObjectSpawnMessage.networkID, obj, s_TinyNetObjectSpawnMessage.frameTick); // If also not, we literally cannot spawn this object and you should feel bad. } else { if (TinyNetLogLevel.logError) { TinyLogger.LogError("Failed to spawn server object, assetId=" + s_TinyNetObjectSpawnMessage.assetIndex + " networkID=" + s_TinyNetObjectSpawnMessage.networkID); } } }