//public void Initialize(bool empty = false) //{ // cache = new Dictionary<string, List<GameObject>>(); // if (empty) // { // keys = new string[] { "" }; // return; // } // for (int i = 0; i < keys.Length; i++) // { // string currentKey = keys[i]; // List<GameObject> local = new List<GameObject>(); // Expand(currentKey, local, defaultCount); // cache.Add(currentKey, local); // } //} public GameObject NetworkEnable(string name, Vector3 position, Quaternion rotation, int group = 0, object[] data = null, bool isSceneObject = false) { if (IN_GAME_MAIN_CAMERA.GameType != GameType.MultiPlayer) { Debug.LogError($"PoolObject.NetworkEnable(): Failed to NetworkEnable prefab, because GameType is not Multiplayer."); return(null); } GameObject go = PickObject(name); PhotonView pv = go.GetComponent <PhotonView>(); if (pv == null) { throw new System.Exception($"PoolObject.NetworkEnable(): Prefab \"{name}\" has not PhotonView component."); } PhotonView[] photonViews = go.GetPhotonViewsInChildren(); int[] viewIDs = new int[photonViews.Length]; for (int i = 0; i < viewIDs.Length; i++) { viewIDs[i] = PhotonNetwork.AllocateViewID(PhotonNetwork.player.ID); } PhotonNetwork.networkingPeer.SendInstantiate(name, position, rotation, group, viewIDs, data, isSceneObject); return(NetworkInstantiate(name, position, rotation, viewIDs[0], viewIDs, (short)(PhotonNetwork.networkingPeer.currentLevelPrefix > 0 ? PhotonNetwork.networkingPeer.currentLevelPrefix : 0), group, data)); #region Old version //for (int i = 0; i < photonViews.Length; i++) //{ // photonViews[i].viewID = viewIDs[i]; // photonViews[i].prefix = prefix; // photonViews[i].instantiationId = instantiationId; //} //if (go.transform != null) //{ // go.transform.position = position; // go.transform.rotation = rotation; //} //peer.StoreInstantiationData(instantiationId, data); //go.SetActive(true); //peer.RemoveInstantiationData(instantiationId); //if (peer.instantiatedObjects.ContainsKey(instantiationId)) //{ // GameObject gameobj = peer.instantiatedObjects[instantiationId]; // string str2 = string.Empty; // if (gameobj != null) // { // foreach (PhotonView view in gameobj.GetPhotonViewsInChildren()) // { // if (view != null) // { // str2 = str2 + view.ToString() + ", "; // } // } // } // object[] args = new object[] { gameobj, instantiationId, peer.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, NetworkingPeer.photonViewList.Count }; // Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} photonViewList.Count {7}.)", args)); // peer.RemoveInstantiatedGO(go, true); //} //peer.instantiatedObjects.Add(instantiationId, go); //return go; #endregion }
private void SynchViewIDs(GameObject go, int[] viewIDs) { PhotonView[] PVs = go.GetPhotonViewsInChildren(); for (int i = 0; i < PVs.Length; i++) { PVs[i].viewID = viewIDs[i]; PVs[i].instantiationId = viewIDs[i]; } }
private int[] ExtractPhotonViewIDs(GameObject go) { PhotonView[] views = go.GetPhotonViewsInChildren(); int[] viewIDs = new int[views.Length]; for (int i = 0; i < viewIDs.Length; i++) { viewIDs[i] = views[i].viewID; } return(viewIDs); }
public static GameObject NetworkInstantiate(string name, Vector3 position, Quaternion rotation, int instantioationId, int[] viewIDs, short prefix = 0, int group = 0, object[] data = null) { GameObject res = (name.StartsWith("RCAsset/") ? CacheResources.RCLoad(name) : CacheResources.Load(name)) as GameObject; if (res == null) { Debug.LogError($"Pool.NetworkInstantiate(): Cannot fint prefab with name \"{name}\"."); return(null); } PhotonView[] views = res.GetPhotonViewsInChildren(); if (views.Length != viewIDs.Length) { throw new System.Exception($"Pool.NetworkInstantiate(): Error in Instantiation(\"{name}\")! The resource's PhotonView count is not the same as in incoming data. {views.Length} != {viewIDs.Length}"); } for (int i = 0; i < views.Length; i++) { views[i].viewID = viewIDs[i]; views[i].prefix = prefix; views[i].instantiationId = instantioationId; } PhotonNetwork.networkingPeer.StoreInstantiationData(instantioationId, data); GameObject go = (GameObject)Object.Instantiate(res, position, rotation); for (int i = 0; i < views.Length; i++) { views[i].viewID = 0; views[i].prefix = -1; views[i].instantiationId = -1; views[i].prefixBackup = -1; } PhotonNetwork.networkingPeer.RemoveInstantiationData(instantioationId); if (PhotonNetwork.networkingPeer.instantiatedObjects.ContainsKey(instantioationId)) { GameObject gameobj = PhotonNetwork.networkingPeer.instantiatedObjects[instantioationId]; string str2 = string.Empty; if (gameobj != null) { foreach (PhotonView view in gameobj.GetPhotonViewsInChildren()) { if (view != null) { str2 = str2 + view.ToString() + ", "; } } } object[] args = new object[] { gameobj, instantioationId, PhotonNetwork.networkingPeer.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, NetworkingPeer.photonViewList.Count }; Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} photonViewList.Count {7}.)", args)); PhotonNetwork.networkingPeer.RemoveInstantiatedGO(go, true); } PhotonNetwork.networkingPeer.instantiatedObjects.Add(instantioationId, go); return(go); }
public override void OnJoinedRoom() { PhotonView[] PVs = localAvatar.GetPhotonViewsInChildren(); for (int i = 0; i < PVs.Length; i++) { PVs[i].RequestOwnership(); } PhotonView LYPV = localYoke.GetPhotonView(); LYPV.RequestOwnership(); }
private void AddressFinalPUNSynch(GameObject go) { NetworkingPeer networkingPeer = PhotonNetwork.networkingPeer; // Send to others, create info //Hashtable instantiateEvent = networkingPeer.SendInstantiate(prefabName, position, rotation, group, viewIDs, data, false); RaiseEventOptions options = new RaiseEventOptions(); bool isGlobalObject = false; options.CachingOption = (isGlobalObject) ? EventCaching.AddToRoomCacheGlobal : EventCaching.AddToRoomCache; PhotonView[] photonViews = go.GetPhotonViewsInChildren(); for (int i = 0; i < photonViews.Length; i++) { photonViews[i].didAwake = false; //photonViews[i].viewID = 0; // why is this included in the original? //photonViews[i].prefix = objLevelPrefix; photonViews[i].prefix = networkingPeer.currentLevelPrefix; //photonViews[i].instantiationId = instantiationId; photonViews[i].instantiationId = go.GetComponent <PhotonView>().viewID; photonViews[i].isRuntimeInstantiated = true; //photonViews[i].instantiationDataField = incomingInstantiationData; photonViews[i].instantiationDataField = null; photonViews[i].didAwake = true; //photonViews[i].viewID = viewsIDs[i]; // with didAwake true and viewID == 0, this will also register the view //photonViews[i].viewID = viewIDs[i]; photonViews[i].viewID = go.GetPhotonViewsInChildren()[i].viewID; } // Send OnPhotonInstantiate callback to newly created GO. // GO will be enabled when instantiated from Prefab and it does not matter if the script is enabled or disabled. go.SendMessage(PhotonNetworkingMessage.OnPhotonInstantiate.ToString(), new PhotonMessageInfo(PhotonNetwork.player, PhotonNetwork.ServerTimestamp, null), SendMessageOptions.DontRequireReceiver); // Instantiate the GO locally (but the same way as if it was done via event). This will also cache the instantiationId //return networkingPeer.DoInstantiate(instantiateEvent, networkingPeer.LocalPlayer, prefabGo); }
public GameObject NetworkInstantiate(string name, Vector3 position, Quaternion rotation, int instantioationId, int[] viewIDs, short prefix = 0, int group = 0, object[] data = null) { GameObject go = PickObject(name); if (!go.GetComponent <PhotonView>()) { Debug.LogError($"PoolObject.NetworkInstantiate(): Prefab with name \"{name}\" has not PhotonView component!"); return(null); } PhotonView[] views = go.GetPhotonViewsInChildren(); for (int i = 0; i < views.Length; i++) { views[i].didAwake = false; views[i].viewID = 0; views[i].prefix = prefix; views[i].instantiationId = instantioationId; views[i].instantiationData = data; views[i].didAwake = true; views[i].viewID = viewIDs[i]; } if (go.transform) { go.transform.position = position; go.transform.rotation = rotation; } go.SetActive(true); PhotonNetwork.networkingPeer.RemoveInstantiationData(instantioationId); if (PhotonNetwork.networkingPeer.instantiatedObjects.ContainsKey(instantioationId)) { GameObject gameobj = PhotonNetwork.networkingPeer.instantiatedObjects[instantioationId]; string str2 = string.Empty; if (gameobj != null) { foreach (PhotonView view in gameobj.GetPhotonViewsInChildren()) { if (view != null) { str2 = str2 + view.ToString() + ", "; } } } object[] args = new object[] { gameobj, instantioationId, PhotonNetwork.networkingPeer.instantiatedObjects.Count, go, str2, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, NetworkingPeer.photonViewList.Count }; Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} photonViewList.Count {7}.)", args)); PhotonNetwork.networkingPeer.RemoveInstantiatedGO(go, true); } PhotonNetwork.networkingPeer.instantiatedObjects.Add(instantioationId, go); return(go); }
public static GameObject InstantiateSceneObject(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data) { if (!connected || (InstantiateInRoomOnly && !inRoom)) { Debug.LogError(string.Concat(new object[] { "Failed to InstantiateSceneObject prefab: ", prefabName, ". Client should be in a room. Current connectionStateDetailed: ", connectionStateDetailed })); return(null); } if (!IsMasterClient) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Client is not the MasterClient in this room."); return(null); } GameObject gameObject = (GameObject)Optimization.Caching.CacheResources.Load(prefabName); if (gameObject == null) { Debug.LogError("Failed to InstantiateSceneObject prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)"); return(null); } if (gameObject.GetComponent <PhotonView>() == null) { Debug.LogError("Failed to InstantiateSceneObject prefab:" + prefabName + ". Prefab must have a PhotonView component."); return(null); } Component[] photonViewsInChildren = gameObject.GetPhotonViewsInChildren(); int[] array = AllocateSceneViewIDs(photonViewsInChildren.Length); if (array == null) { Debug.LogError(string.Concat(new object[] { "Failed to InstantiateSceneObject prefab: ", prefabName, ". No ViewIDs are free to use. Max is: ", MAX_VIEW_IDS })); return(null); } Hashtable evData = networkingPeer.SendInstantiate(prefabName, position, rotation, group, array, data, true); return(networkingPeer.DoInstantiate(evData, networkingPeer.mLocalActor, gameObject)); }
public static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, int group, object[] data) { if (!connected || (InstantiateInRoomOnly && !inRoom)) { Debug.LogError(string.Concat(new object[] { "Failed to Instantiate prefab: ", prefabName, ". Client should be in a room. Current connectionStateDetailed: ", connectionStateDetailed })); return(null); } GameObject gameObject = prefabName.StartsWith("RCAsset/") ? Optimization.Caching.CacheResources.RCLoad(prefabName) : (GameObject)Optimization.Caching.CacheResources.Load(prefabName); // if (!UsePrefabCache || !PrefabCache.TryGetValue(prefabName, out gameObject)) //{ // gameObject = // if (UsePrefabCache) // { // PrefabCache.Add(prefabName, gameObject); // } //} if (gameObject == null) { Debug.LogError("Failed to Instantiate prefab: " + prefabName + ". Verify the Prefab is in a Resources folder (and not in a subfolder)"); return(null); } if (gameObject.GetComponent <PhotonView>() == null) { Debug.LogError("Failed to Instantiate prefab:" + prefabName + ". Prefab must have a PhotonView component."); return(null); } Component[] photonViewsInChildren = gameObject.GetPhotonViewsInChildren(); int[] array = new int[photonViewsInChildren.Length]; for (int i = 0; i < array.Length; i++) { array[i] = AllocateViewID(player.ID); } networkingPeer.SendInstantiate(prefabName, position, rotation, group, array, data, false); return(Optimization.Caching.Pool.NetworkInstantiate(prefabName, position, rotation, array[0], array, networkingPeer.currentLevelPrefix, group, data)); //Hashtable evData = networkingPeer.SendInstantiate(prefabName, position, rotation, group, array, data, false); //return networkingPeer.DoInstantiate(evData, networkingPeer.mLocalActor, gameObject); }
private GameObject SetViewIDs(ref GameObject go) { NetworkingPeer networkingPeer = PhotonNetwork.networkingPeer; PhotonView[] views = go.GetPhotonViewsInChildren(); //Debug.Log("Found " + views.Length + " photon views in " + go.name + " object and its children"); int[] viewIDs = new int[views.Length]; for (int i = 0; i < viewIDs.Length; i++) // ignore the main gameobject { //Debug.Log("Instantiate prefabName: " + prefabName + " player.ID: " + player.ID); viewIDs[i] = PhotonNetwork.AllocateViewID(); //Debug.Log("Allocated an id of " + viewIDs[i]); views[i].viewID = viewIDs[i]; views[i].instantiationId = viewIDs[i]; //Debug.Log("Assigning view id of " + viewIDs[i] + ", so now the view id is " + go.GetPhotonView().viewID + " for gameobject " + go.name); networkingPeer.RegisterPhotonView(views[i]); } return(go); }
private GameObject HandlePUNStuff(GameObject go, int[] viewIDs) { go = AttachPhotonViews(go); go = AttachPhotonTransformViews(go); if (viewIDs == null) { SetViewIDs(ref go); } else { if (go.GetPhotonViewsInChildren().Length != viewIDs.Length) { UnityEngine.Debug.LogError("Prefab mismatch encountered! Number of children encountered differs between nodes."); } SynchViewIDs(go, viewIDs); } AddressFinalPUNSynch(go); return(go); }
void SendCurrentState(string playerRequesting) { if (PhotonNetwork.isMasterClient) { PhotonView[] objectsInCupB = items.GetPhotonViewsInChildren(); if (objectsInCupB != null) { foreach (PhotonView p in objectsInCupB) { photonView.RPC("DropItem", PhotonTargets.Others, p.viewID); //Make sure all spawneditems are where they should be on new player join } } if (lockLight != null) { photonView.RPC("ReceiveCurrentState", PhotonTargets.Others, playerRequesting, lockLight.IsLocked(), doorTrigger.IsClosed, transform.parent.transform.position); //Gather the values and send back } else { photonView.RPC("ReceiveCurrentState", PhotonTargets.Others, playerRequesting, false, doorTrigger.IsClosed, transform.parent.transform.position); //Gather the values and send back } } }
/// <summary>Removes GameObject and the PhotonViews on it from local lists and optionally updates remotes. GameObject gets destroyed at end.</summary> /// <remarks> /// This method might fail and quit early due to several tests. /// </remarks> /// <param name="go">GameObject to cleanup.</param> /// <param name="localOnly">For localOnly, tests of control are skipped and the server is not updated.</param> protected internal void RemoveInstantiatedGO(GameObject go, bool localOnly) { if (go == null) { Debug.LogError("Failed to 'network-remove' GameObject because it's null."); return; } // Don't remove the GO if it doesn't have any PhotonView PhotonView[] views = go.GetComponentsInChildren<PhotonView>(true); if (views == null || views.Length <= 0) { Debug.LogError("Failed to 'network-remove' GameObject because has no PhotonView components: " + go); return; } PhotonView viewZero = views[0]; int creatorId = viewZero.CreatorActorNr; // creatorId of obj is needed to delete EvInstantiate (only if it's from that user) int instantiationId = viewZero.instantiationId; // actual, live InstantiationIds start with 1 and go up // Don't remove GOs that are owned by others (unless this is the master and the remote player left) if (!localOnly) { if (!viewZero.isMine) { Debug.LogError("Failed to 'network-remove' GameObject. Client is neither owner nor masterClient taking over for owner who left: " + viewZero); return; } // Don't remove the Instantiation from the server, if it doesn't have a proper ID if (instantiationId < 1) { Debug.LogError("Failed to 'network-remove' GameObject because it is missing a valid InstantiationId on view: " + viewZero + ". Not Destroying GameObject or PhotonViews!"); return; } } // cleanup instantiation (event and local list) if (!localOnly) { this.ServerCleanInstantiateAndDestroy(instantiationId, creatorId, viewZero.isRuntimeInstantiated); // server cleaning } // cleanup PhotonViews and their RPCs events (if not localOnly) for (int j = views.Length - 1; j >= 0; j--) { PhotonView view = views[j]; if (view == null) { continue; } // we only destroy/clean PhotonViews that were created by PhotonNetwork.Instantiate (and those have an instantiationId!) if (view.instantiationId >= 1) { this.LocalCleanPhotonView(view); } if (!localOnly) { this.OpCleanRpcBuffer(view); } } if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) { Debug.Log("Network destroy Instantiated GO: " + go.name); } if (this.ObjectPool != null) { PhotonView[] photonViews = go.GetPhotonViewsInChildren(); for (int i = 0; i < photonViews.Length; i++) { photonViews[i].viewID = 0; // marks the PV as not being in use currently. } this.ObjectPool.Destroy(go); } else { GameObject.Destroy(go); } }
internal GameObject DoInstantiate(Hashtable evData, PhotonPlayer photonPlayer, GameObject resourceGameObject) { // some values always present: string prefabName = (string)evData[(byte)0]; int serverTime = (int)evData[(byte)6]; int instantiationId = (int)evData[(byte)7]; Vector3 position; if (evData.ContainsKey((byte)1)) { position = (Vector3)evData[(byte)1]; } else { position = Vector3.zero; } Quaternion rotation = Quaternion.identity; if (evData.ContainsKey((byte)2)) { rotation = (Quaternion)evData[(byte)2]; } int group = 0; if (evData.ContainsKey((byte)3)) { group = (int)evData[(byte)3]; } short objLevelPrefix = 0; if (evData.ContainsKey((byte)8)) { objLevelPrefix = (short)evData[(byte)8]; } int[] viewsIDs; if (evData.ContainsKey((byte)4)) { viewsIDs = (int[])evData[(byte)4]; } else { viewsIDs = new int[1] { instantiationId }; } object[] incomingInstantiationData; if (evData.ContainsKey((byte)5)) { incomingInstantiationData = (object[])evData[(byte)5]; } else { incomingInstantiationData = null; } // SetReceiving filtering if (group != 0 && !this.allowedReceivingGroups.Contains(group)) { return null; // Ignore group } // load prefab, if it wasn't loaded before (calling methods might do this) if (resourceGameObject == null) { if (!NetworkingPeer.UsePrefabCache || !NetworkingPeer.PrefabCache.TryGetValue(prefabName, out resourceGameObject)) { resourceGameObject = (GameObject)Resources.Load(prefabName, typeof(GameObject)); if (NetworkingPeer.UsePrefabCache) { NetworkingPeer.PrefabCache.Add(prefabName, resourceGameObject); } } if (resourceGameObject == null) { Debug.LogError("PhotonNetwork error: Could not Instantiate the prefab [" + prefabName + "]. Please verify you have this gameobject in a Resources folder."); return null; } } // now modify the loaded "blueprint" object before it becomes a part of the scene (by instantiating it) PhotonView[] resourcePVs = resourceGameObject.GetPhotonViewsInChildren(); if (resourcePVs.Length != viewsIDs.Length) { throw new Exception("Error in Instantiation! The resource's PhotonView count is not the same as in incoming data."); } for (int i = 0; i < viewsIDs.Length; i++) { // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below // so we only set the viewID and instantiationId now. the instantiationData can be fetched resourcePVs[i].viewID = viewsIDs[i]; resourcePVs[i].prefix = objLevelPrefix; resourcePVs[i].instantiationId = instantiationId; } this.StoreInstantiationData(instantiationId, incomingInstantiationData); // load the resource and set it's values before instantiating it: // Debug.Log("PreInstantiate"); GameObject go = (GameObject)GameObject.Instantiate(resourceGameObject, position, rotation); // Debug.LogWarning("PostInstantiate"); for (int i = 0; i < viewsIDs.Length; i++) { // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below // so we only set the viewID and instantiationId now. the instantiationData can be fetched resourcePVs[i].viewID = 0; resourcePVs[i].prefix = -1; resourcePVs[i].prefixBackup = -1; resourcePVs[i].instantiationId = -1; } this.RemoveInstantiationData(instantiationId); //TODO: remove this debug check if (this.instantiatedObjects.ContainsKey(instantiationId)) { GameObject knownGo = this.instantiatedObjects[instantiationId]; string pvaInfo = ""; PhotonView[] pva; if (knownGo != null) { pva = knownGo.GetPhotonViewsInChildren(); foreach (PhotonView view in pva) { if (view == null) continue; pvaInfo += view.ToString() + ", "; } } Debug.LogError(string.Format("Adding GO \"{0}\" (instantiationID: {1}) to instantiatedObjects failed. instantiatedObjects.Count: {2}. Object taking the same place: {3}. Views on it: {4}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} this.photonViewList.Count {7}.)", go, instantiationId, this.instantiatedObjects.Count, knownGo, pvaInfo, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, this.photonViewList.Count)); this.instantiatedObjects.Remove(instantiationId); // TODO: check if simple remove is ok in all cases. } this.instantiatedObjects.Add(instantiationId, go); //TODO check if instantiatedObjects is (still) needed // Send mono event // TOD move this callback and script-caching into a method! there should be one already... object[] messageInfoParam = new object[1]; messageInfoParam[0] = new PhotonMessageInfo(photonPlayer, serverTime, null); MonoBehaviour[] monos = go.GetComponentsInChildren<MonoBehaviour>(); for (int index = 0; index < monos.Length; index++) { MonoBehaviour mono = monos[index]; MethodInfo methodI = this.GetCachedMethod(mono, PhotonNetworkingMessage.OnPhotonInstantiate); if (methodI != null) { object result = methodI.Invoke((object)mono, messageInfoParam); if (methodI.ReturnType == typeof(System.Collections.IEnumerator)) { mono.StartCoroutine((IEnumerator)result); } } } return go; }
internal GameObject DoInstantiate(Hashtable evData, PhotonPlayer photonPlayer, GameObject resourceGameObject) { // some values always present: string prefabName = (string)evData[(byte)0]; int serverTime = (int)evData[(byte)6]; int instantiationId = (int)evData[(byte)7]; Vector3 position; if (evData.ContainsKey((byte)1)) { position = (Vector3)evData[(byte)1]; } else { position = Vector3.zero; } Quaternion rotation = Quaternion.identity; if (evData.ContainsKey((byte)2)) { rotation = (Quaternion)evData[(byte)2]; } int group = 0; if (evData.ContainsKey((byte)3)) { group = (int)evData[(byte)3]; } short objLevelPrefix = 0; if (evData.ContainsKey((byte)8)) { objLevelPrefix = (short)evData[(byte)8]; } int[] viewsIDs; if (evData.ContainsKey((byte)4)) { viewsIDs = (int[])evData[(byte)4]; } else { viewsIDs = new int[1] { instantiationId }; } object[] incomingInstantiationData; if (evData.ContainsKey((byte)5)) { incomingInstantiationData = (object[])evData[(byte)5]; } else { incomingInstantiationData = null; } // SetReceiving filtering if (group != 0 && !this.allowedReceivingGroups.Contains(group)) { return null; // Ignore group } // load prefab, if it wasn't loaded before (calling methods might do this) if (resourceGameObject == null) { if (!NetworkingPeer.UsePrefabCache || !NetworkingPeer.PrefabCache.TryGetValue(prefabName, out resourceGameObject)) { resourceGameObject = (GameObject)Resources.Load(prefabName, typeof(GameObject)); if (NetworkingPeer.UsePrefabCache) { NetworkingPeer.PrefabCache.Add(prefabName, resourceGameObject); } } if (resourceGameObject == null) { Debug.LogError("PhotonNetwork error: Could not Instantiate the prefab [" + prefabName + "]. Please verify you have this gameobject in a Resources folder."); return null; } } // now modify the loaded "blueprint" object before it becomes a part of the scene (by instantiating it) PhotonView[] resourcePVs = resourceGameObject.GetPhotonViewsInChildren(); if (resourcePVs.Length != viewsIDs.Length) { throw new Exception("Error in Instantiation! The resource's PhotonView count is not the same as in incoming data."); } for (int i = 0; i < viewsIDs.Length; i++) { // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below // so we only set the viewID and instantiationId now. the instantiationData can be fetched resourcePVs[i].viewID = viewsIDs[i]; resourcePVs[i].prefix = objLevelPrefix; resourcePVs[i].instantiationId = instantiationId; } this.StoreInstantiationData(instantiationId, incomingInstantiationData); // load the resource and set it's values before instantiating it: GameObject go = (GameObject)GameObject.Instantiate(resourceGameObject, position, rotation); for (int i = 0; i < viewsIDs.Length; i++) { // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below // so we only set the viewID and instantiationId now. the instantiationData can be fetched resourcePVs[i].viewID = 0; resourcePVs[i].prefix = -1; resourcePVs[i].prefixBackup = -1; resourcePVs[i].instantiationId = -1; } this.RemoveInstantiationData(instantiationId); // Send OnPhotonInstantiate callback to newly created GO. // GO will be enabled when instantiated from Prefab and it does not matter if the script is enabled or disabled. go.SendMessage(PhotonNetworkingMessage.OnPhotonInstantiate.ToString(), new PhotonMessageInfo(photonPlayer, serverTime, null), SendMessageOptions.DontRequireReceiver); return go; }
/// <summary> /// This returns -1 if the GO could not be found in list of instantiatedObjects. /// </summary> public int GetInstantiatedObjectsId(GameObject go) { int id = -1; if (go == null) { this.DebugReturn(DebugLevel.ERROR, "GetInstantiatedObjectsId() for GO == null."); return id; } PhotonView[] pvs = go.GetPhotonViewsInChildren(); if (pvs != null && pvs.Length > 0 && pvs[0] != null) { return pvs[0].instantiationId; } if (DebugOut == DebugLevel.ALL) { this.DebugReturn(DebugLevel.ALL, "GetInstantiatedObjectsId failed for GO: " + go); } return id; }
/// <summary> /// This returns -1 if the GO could not be found in list of instantiatedObjects. /// </summary> public int GetInstantiatedObjectsId(GameObject go) { int id = -1; if (go == null) { Debug.LogError("GetInstantiatedObjectsId() for GO == null."); return id; } PhotonView[] pvs = go.GetPhotonViewsInChildren(); if (pvs != null && pvs.Length > 0 && pvs[0] != null) { return pvs[0].instantiationId; } if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) UnityEngine.Debug.Log("GetInstantiatedObjectsId failed for GO: " + go); return id; }
internal GameObject DoInstantiate(Hashtable evData, PhotonPlayer photonPlayer, GameObject resourceGameObject) { // some values always present: string prefabName = (string)evData[(byte)0]; int serverTime = (int)evData[(byte)6]; int instantiationId = (int)evData[(byte)7]; Vector3 position; if (evData.ContainsKey((byte)1)) { position = (Vector3)evData[(byte)1]; } else { position = Vector3.zero; } Quaternion rotation = Quaternion.identity; if (evData.ContainsKey((byte)2)) { rotation = (Quaternion)evData[(byte)2]; } int group = 0; if (evData.ContainsKey((byte)3)) { group = (int)evData[(byte)3]; } short objLevelPrefix = 0; if (evData.ContainsKey((byte)8)) { objLevelPrefix = (short)evData[(byte)8]; } int[] viewsIDs; if (evData.ContainsKey((byte)4)) { viewsIDs = (int[])evData[(byte)4]; } else { viewsIDs = new int[1] { instantiationId }; } object[] incomingInstantiationData; if (evData.ContainsKey((byte)5)) { incomingInstantiationData = (object[])evData[(byte)5]; } else { incomingInstantiationData = null; } // SetReceiving filtering if (group != 0 && !this.allowedReceivingGroups.Contains(group)) { return null; // Ignore group } // load prefab, if it wasn't loaded before (calling methods might do this) if (resourceGameObject == null) { if (!NetworkingPeer.UsePrefabCache || !NetworkingPeer.PrefabCache.TryGetValue(prefabName, out resourceGameObject)) { resourceGameObject = (GameObject)Resources.Load(prefabName, typeof(GameObject)); if (NetworkingPeer.UsePrefabCache) { NetworkingPeer.PrefabCache.Add(prefabName, resourceGameObject); } } if (resourceGameObject == null) { Debug.LogError("PhotonNetwork error: Could not Instantiate the prefab [" + prefabName + "]. Please verify you have this gameobject in a Resources folder."); return null; } } // now modify the loaded "blueprint" object before it becomes a part of the scene (by instantiating it) PhotonView[] resourcePVs = resourceGameObject.GetPhotonViewsInChildren(); if (resourcePVs.Length != viewsIDs.Length) { throw new Exception("Error in Instantiation! The resource's PhotonView count is not the same as in incoming data."); } for (int i = 0; i < viewsIDs.Length; i++) { // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below // so we only set the viewID and instantiationId now. the instantiationData can be fetched resourcePVs[i].viewID = viewsIDs[i]; resourcePVs[i].prefix = objLevelPrefix; resourcePVs[i].instantiationId = instantiationId; } this.StoreInstantiationData(instantiationId, incomingInstantiationData); // load the resource and set it's values before instantiating it: GameObject go = (GameObject)GameObject.Instantiate(resourceGameObject, position, rotation); for (int i = 0; i < viewsIDs.Length; i++) { // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below // so we only set the viewID and instantiationId now. the instantiationData can be fetched resourcePVs[i].viewID = 0; resourcePVs[i].prefix = -1; resourcePVs[i].prefixBackup = -1; resourcePVs[i].instantiationId = -1; } this.RemoveInstantiationData(instantiationId); //TODO: remove this debug check if (this.instantiatedObjects.ContainsKey(instantiationId)) { GameObject knownGo = this.instantiatedObjects[instantiationId]; string pvaInfo = ""; PhotonView[] pva; if (knownGo != null) { pva = knownGo.GetPhotonViewsInChildren(); foreach (PhotonView view in pva) { if (view == null) continue; pvaInfo += view.ToString() + ", "; } } Debug.LogError(string.Format("DoInstantiate re-defines a GameObject. Destroying old entry! New: '{0}' (instantiationID: {1}) Old: {3}. PhotonViews on old: {4}. instantiatedObjects.Count: {2}. PhotonNetwork.lastUsedViewSubId: {5} PhotonNetwork.lastUsedViewSubIdStatic: {6} this.photonViewList.Count {7}.)", go, instantiationId, this.instantiatedObjects.Count, knownGo, pvaInfo, PhotonNetwork.lastUsedViewSubId, PhotonNetwork.lastUsedViewSubIdStatic, this.photonViewList.Count)); //this.instantiatedObjects.Remove(instantiationId); // TODO: check if simple remove is ok in all cases. Maybe better Destroy!? this.RemoveInstantiatedGO(knownGo, true); } this.instantiatedObjects.Add(instantiationId, go); //TODO check if instantiatedObjects is (still) needed // Send OnPhotonInstantiate callback to newly created GO. // GO will be enabled when instantiated from Prefab and it does not matter if the script is enabled or disabled. go.SendMessage(PhotonNetworkingMessage.OnPhotonInstantiate.ToString(), new PhotonMessageInfo(photonPlayer, serverTime, null), SendMessageOptions.DontRequireReceiver); return go; }