private void OnNetCreate(NetCreatePacket obj) { //Debug.Log($"[Client] - NetObject {obj.TypeName} created with id {obj.NetID} and parent id {obj.ParentID}"); DebugUtils.Assert(!NetObjectExists(obj.NetID), $"Net object with id {obj.NetID} already exists on the client."); var netObj = new INetObject(this, obj.NetObjectType, obj.EntityType, obj.NetID, obj.CreateData); netObjects.Add(obj.NetID, netObj); // If the corresponding obj has a parent, then we need to go up the chain // of parents and find the first one that has an OnCreate method defined // for this type of net object. If we don't find anything, then this net // object becomes its own Game Object with the NetObject component. if (obj.ParentID != -1) { netObj.SetParent(obj.ParentID); netObjects[obj.ParentID].AddChild(netObj.NetID); // Recursively try and find parent that handles creation of this type // If no parents have defined a handler, then we need to create a game object // with a NetObject component. if (TryParentCreate(obj.ParentID, netObj)) { return; } } netObj.IsGameObject = true; var go = CreateGameObject(netObj); }
// @Note: Right now parent-child relationships have to be established BEFORE adding // the child to the NetObjectManager so when the packet is sent we can set the ParentID. public void AddNetObject(NetObject netObj) { // By using a queue we can traverse the hierarchy in a BFS order. This guarantees that // parents are created before children. var queue = new Queue <NetObject>(); queue.Enqueue(netObj); while (queue.Count > 0) { var obj = queue.Dequeue(); foreach (var childToAdd in obj.ChildrenToBeAdded) { queue.Enqueue(childToAdd); } obj.ClearChildrenToBeAdded(); DebugUtils.Assert(!netObjects.ContainsKey(obj.ID), $"NetObject with ID {obj.ID} already exists!"); // Order matters when creating net objects. Children can't be added before their parents. DebugUtils.Assert(!obj.HasParent || netObjects.ContainsKey(obj.ParentID), $"NetObject[{obj.ID}]'s parent with id {obj.ParentID} hasn't been added yet! !"); netObjects.Add(obj.ID, obj); obj.Added = true; //Debug.Log($"[Server] - Adding {obj.TypeName} net object {obj.ID} has parent {obj.HasParent}"); DebugUtils.Assert(obj.NetObjectType != NetObjectType.NOTHING || obj.EntityType != EntityType.NOTHING, "Can't have NOTHING for both fields EntityType and NetObjectType"); var packet = new NetCreatePacket { NetID = obj.ID, NetObjectType = obj.NetObjectType, EntityType = obj.EntityType, ParentID = obj.HasParent ? obj.ParentID : -1, CreateData = obj.CreateData }; if (obj.SendToAllClients) { server.SendToAllClients(packet); } else { server.SendToSingleClient(packet, obj.ClientID); } } }