Incoming
How do I use Incoming
Below are practical examples compiled from projects for learning and reference purposes
Featured Snippets
File name: NetworkingPeer.cs
Copy
1411 public void OnStatusChanged(StatusCode statusCode)
1412 {
1413 if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1414 Debug.Log(string.Format("OnStatusChanged: {0}", statusCode.ToString()));
1415
1416 switch (statusCode)
1417 {
1418 case StatusCode.Connect:
1419 if (this.State == global::PeerState.ConnectingToNameServer)
1420 {
1421 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1422 Debug.Log("Connected to NameServer.");
1423
1424 this.server = ServerConnection.NameServer;
1425 if (this.CustomAuthenticationValues != null)
1426 {
1427 this.CustomAuthenticationValues.Secret = null; // when connecting to NameServer, invalidate any auth values
1428 }
1429 }
1430
1431 if (this.State == global::PeerState.ConnectingToGameserver)
1432 {
1433 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1434 Debug.Log("Connected to gameserver.");
1435
1436 this.server = ServerConnection.GameServer;
1437 this.State = global::PeerState.ConnectedToGameserver;
1438 }
1439
1440 if (this.State == global::PeerState.ConnectingToMasterserver)
1441 {
1442 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
1443 Debug.Log("Connected to masterserver.");
1444
1445 this.server = ServerConnection.MasterServer;
1446 this.State = global::PeerState.ConnectedToMaster;
1447
1448 if (this.IsInitialConnect)
1449 {
1450 this.IsInitialConnect = false; // after handling potential initial-connect issues with special messages, we are now sure we can reach a server
1451 SendMonoMessage(PhotonNetworkingMessage.OnConnectedToPhoton);
1452 }
1453 }
1454
1455 this.EstablishEncryption(); // always enable encryption
1456
1457 if (this.IsAuthorizeSecretAvailable)
1458 {
1459 // if we have a token we don't have to wait for encryption (it is encrypted anyways, so encryption is just optional later on)
1460 this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString());
1461 if (this.didAuthenticate)
1462 {
1463 this.State = global::PeerState.Authenticating;
1464 }
1465 }
1466 break;
1467
1468 case StatusCode.EncryptionEstablished:
1469 // on nameserver, the "process" is stopped here, so the developer/game can either get regions or authenticate with a specific region
1470 if (this.server == ServerConnection.NameServer)
1471 {
1472 this.State = global::PeerState.ConnectedToNameServer;
1473
1474 if (!this.didAuthenticate && this.CloudRegion == CloudRegionCode.none)
1475 {
1476 // this client is not setup to connect to a default region. find out which regions there are!
1477 this.OpGetRegions(this.mAppId);
1478 }
1479 }
1480
1481 // we might need to authenticate automatically now, so the client can do anything at all
1482 if (!this.didAuthenticate && (!this.IsUsingNameServer || this.CloudRegion != CloudRegionCode.none))
1483 {
1484 // once encryption is availble, the client should send one (secure) authenticate. it includes the AppId (which identifies your app on the Photon Cloud)
1485 this.didAuthenticate = this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString());
1486 if (this.didAuthenticate)
1487 {
1488 this.State = global::PeerState.Authenticating;
1489 }
1490 }
1491 break;
1492
1493 case StatusCode.EncryptionFailedToEstablish:
1494 Debug.LogError("Encryption wasn't established: " + statusCode + ". Going to authenticate anyways.");
1495 this.OpAuthenticate(this.mAppId, this.mAppVersionPun, this.PlayerName, this.CustomAuthenticationValues, this.CloudRegion.ToString()); // TODO: check if there are alternatives
1496 break;
1497
1498 case StatusCode.Disconnect:
1499 this.didAuthenticate = false;
1500 this.isFetchingFriends = false;
1501 if (server == ServerConnection.GameServer) this.LeftRoomCleanup();
1502 if (server == ServerConnection.MasterServer) this.LeftLobbyCleanup();
1503
1504 if (this.State == global::PeerState.DisconnectingFromMasterserver)
1505 {
1506 if (this.Connect(this.mGameserver, ServerConnection.GameServer))
1507 {
1508 this.State = global::PeerState.ConnectingToGameserver;
1509 }
1510 }
1511 else if (this.State == global::PeerState.DisconnectingFromGameserver || this.State == global::PeerState.DisconnectingFromNameServer)
1512 {
1513 if (this.Connect(this.MasterServerAddress, ServerConnection.MasterServer))
1514 {
1515 this.State = global::PeerState.ConnectingToMasterserver;
1516 }
1517 }
1518 else
1519 {
1520 if (this.CustomAuthenticationValues != null)
1521 {
1522 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1523 }
1524
1525 this.State = global::PeerState.PeerCreated; // if we set another state here, we could keep clients from connecting in OnDisconnectedFromPhoton right here.
1526 SendMonoMessage(PhotonNetworkingMessage.OnDisconnectedFromPhoton);
1527 }
1528 break;
1529
1530 case StatusCode.SecurityExceptionOnConnect:
1531 case StatusCode.ExceptionOnConnect:
1532 this.State = global::PeerState.PeerCreated;
1533 if (this.CustomAuthenticationValues != null)
1534 {
1535 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1536 }
1537
1538 DisconnectCause cause = (DisconnectCause)statusCode;
1539 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1540 break;
1541
1542 case StatusCode.Exception:
1543 if (this.IsInitialConnect)
1544 {
1545 Debug.LogError("Exception while connecting to: " + this.ServerAddress + ". Check if the server is available.");
1546 if (this.ServerAddress == null || this.ServerAddress.StartsWith("127.0.0.1"))
1547 {
1548 Debug.LogWarning("The server address is 127.0.0.1 (localhost): Make sure the server is running on this machine. Android and iOS emulators have their own localhost.");
1549 if (this.ServerAddress == this.mGameserver)
1550 {
1551 Debug.LogWarning("This might be a misconfiguration in the game server config. You need to edit it to a (public) address.");
1552 }
1553 }
1554
1555 this.State = global::PeerState.PeerCreated;
1556 cause = (DisconnectCause)statusCode;
1557 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1558 }
1559 else
1560 {
1561 this.State = global::PeerState.PeerCreated;
1562
1563 cause = (DisconnectCause)statusCode;
1564 SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, cause);
1565 }
1566
1567 this.Disconnect();
1568 break;
1569
1570 case StatusCode.TimeoutDisconnect:
1571 case StatusCode.ExceptionOnReceive:
1572 case StatusCode.DisconnectByServer:
1573 case StatusCode.DisconnectByServerLogic:
1574 case StatusCode.DisconnectByServerUserLimit:
1575 if (this.IsInitialConnect)
1576 {
1577 Debug.LogWarning(statusCode + " while connecting to: " + this.ServerAddress + ". Check if the server is available.");
1578
1579 cause = (DisconnectCause)statusCode;
1580 SendMonoMessage(PhotonNetworkingMessage.OnFailedToConnectToPhoton, cause);
1581 }
1582 else
1583 {
1584 cause = (DisconnectCause)statusCode;
1585 SendMonoMessage(PhotonNetworkingMessage.OnConnectionFail, cause);
1586 }
1587 if (this.CustomAuthenticationValues != null)
1588 {
1589 this.CustomAuthenticationValues.Secret = null; // invalidate any custom auth secrets
1590 }
1591
1592 this.Disconnect();
1593 break;
1594
1595 case StatusCode.SendError:
1596 // this.mListener.clientErrorReturn(statusCode);
1597 break;
1598
1599 case StatusCode.QueueOutgoingReliableWarning:
1600 case StatusCode.QueueOutgoingUnreliableWarning:
1601 case StatusCode.QueueOutgoingAcksWarning:
1602 case StatusCode.QueueSentWarning:
1603 // this.mListener.warningReturn(statusCode);
1604 break;
1605
1606 case StatusCode.QueueIncomingReliableWarning:
1607 case StatusCode.QueueIncomingUnreliableWarning:
1608 Debug.Log(statusCode + ". This client buffers many incoming messages. This is OK temporarily. With lots of these warnings, check if you send too much or execute messages too slow. " + (PhotonNetwork.isMessageQueueRunning? "":"Your isMessageQueueRunning is false. This can cause the issue temporarily.") );
1609 break;
1610
1611 // // TCP "routing" is an option of Photon that's not currently needed (or supported) by PUN
1612 //case StatusCode.TcpRouterResponseOk:
1613 // break;
1614 //case StatusCode.TcpRouterResponseEndpointUnknown:
1615 //case StatusCode.TcpRouterResponseNodeIdUnknown:
1616 //case StatusCode.TcpRouterResponseNodeNotReady:
1617
1618 // this.DebugReturn(DebugLevel.ERROR, "Unexpected router response: " + statusCode);
1619 // break;
1620
1621 default:
1622
1623 // this.mListener.serverErrorReturn(statusCode.value());
1624 Debug.LogError("Received unknown status code: " + statusCode);
1625 break;
1626 }
1627
1628 this.externalListener.OnStatusChanged(statusCode);
1629 }
File name: NetworkingPeer.cs
Copy
1631 public void OnEvent(EventData photonEvent)
1632 {
1633 if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
1634 Debug.Log(string.Format("OnEvent: {0}", photonEvent.ToString()));
1635
1636 int actorNr = -1;
1637 PhotonPlayer originatingPlayer = null;
1638
1639 if (photonEvent.Parameters.ContainsKey(ParameterCode.ActorNr))
1640 {
1641 actorNr = (int)photonEvent[ParameterCode.ActorNr];
1642 if (this.mActors.ContainsKey(actorNr))
1643 {
1644 originatingPlayer = (PhotonPlayer)this.mActors[actorNr];
1645 }
1646 //else
1647 //{
1648 // // the actor sending this event is not in actorlist. this is usually no problem
1649 // if (photonEvent.Code != (byte)LiteOpCode.Join)
1650 // {
1651 // Debug.LogWarning("Received event, but we do not have this actor: " + actorNr);
1652 // }
1653 //}
1654 }
1655
1656 switch (photonEvent.Code)
1657 {
1658 case PunEvent.OwnershipRequest:
1659 {
1660 int[] requestValues = (int[]) photonEvent.Parameters[ParameterCode.CustomEventContent];
1661 int requestedViewId = requestValues[0];
1662 int currentOwner = requestValues[1];
1663 Debug.Log("Ev OwnershipRequest: " + photonEvent.Parameters.ToStringFull() + " ViewID: " + requestedViewId + " from: " + currentOwner + " Time: " + Environment.TickCount%1000);
1664
1665 PhotonView requestedView = PhotonView.Find(requestedViewId);
1666 if (requestedView == null)
1667 {
1668 Debug.LogWarning("Can't find PhotonView of incoming OwnershipRequest. ViewId not found: " + requestedViewId);
1669 break;
1670 }
1671
1672 Debug.Log("Ev OwnershipRequest PhotonView.ownershipTransfer: " + requestedView.ownershipTransfer + " .ownerId: " + requestedView.ownerId + " isOwnerActive: " + requestedView.isOwnerActive + ". This client's player: " + PhotonNetwork.player.ToStringFull());
1673
1674 switch (requestedView.ownershipTransfer)
1675 {
1676 case OwnershipOption.Fixed:
1677 Debug.LogWarning("Ownership mode == fixed. Ignoring request.");
1678 break;
1679 case OwnershipOption.Takeover:
1680 if (currentOwner == requestedView.ownerId)
1681 {
1682 // a takeover is successful automatically, if taken from current owner
1683 requestedView.ownerId = actorNr;
1684 }
1685 break;
1686 case OwnershipOption.Request:
1687 if (currentOwner == PhotonNetwork.player.ID || PhotonNetwork.player.isMasterClient)
1688 {
1689 if ((requestedView.ownerId == PhotonNetwork.player.ID) || (PhotonNetwork.player.isMasterClient && !requestedView.isOwnerActive))
1690 {
1691 SendMonoMessage(PhotonNetworkingMessage.OnOwnershipRequest, new object[] {requestedView, originatingPlayer});
1692 }
1693 }
1694 break;
1695 default:
1696 break;
1697 }
1698 }
1699 break;
1700
1701 case PunEvent.OwnershipTransfer:
1702 {
1703 int[] transferViewToUserID = (int[]) photonEvent.Parameters[ParameterCode.CustomEventContent];
1704 Debug.Log("Ev OwnershipTransfer. ViewID " + transferViewToUserID[0] + " to: " + transferViewToUserID[1] + " Time: " + Environment.TickCount%1000);
1705
1706 int requestedViewId = transferViewToUserID[0];
1707 int newOwnerId = transferViewToUserID[1];
1708
1709 PhotonView pv = PhotonView.Find(requestedViewId);
1710 pv.ownerId = newOwnerId;
1711
1712 break;
1713 }
1714 case EventCode.GameList:
1715 {
1716 this.mGameList = new Dictionary
1717 Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList];
1718 foreach (DictionaryEntry game in games)
1719 {
1720 string gameName = (string)game.Key;
1721 this.mGameList[gameName] = new RoomInfo(gameName, (Hashtable)game.Value);
1722 }
1723 mGameListCopy = new RoomInfo[mGameList.Count];
1724 mGameList.Values.CopyTo(mGameListCopy, 0);
1725 SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate);
1726 break;
1727 }
1728
1729 case EventCode.GameListUpdate:
1730 {
1731 Hashtable games = (Hashtable)photonEvent[ParameterCode.GameList];
1732 foreach (DictionaryEntry room in games)
1733 {
1734 string gameName = (string)room.Key;
1735 RoomInfo game = new RoomInfo(gameName, (Hashtable)room.Value);
1736 if (game.removedFromList)
1737 {
1738 this.mGameList.Remove(gameName);
1739 }
1740 else
1741 {
1742 this.mGameList[gameName] = game;
1743 }
1744 }
1745 this.mGameListCopy = new RoomInfo[this.mGameList.Count];
1746 this.mGameList.Values.CopyTo(this.mGameListCopy, 0);
1747 SendMonoMessage(PhotonNetworkingMessage.OnReceivedRoomListUpdate);
1748 break;
1749 }
1750
1751 case EventCode.QueueState:
1752 // not used anymore
1753 break;
1754
1755 case EventCode.AppStats:
1756 // Debug.LogInfo("Received stats!");
1757 this.mPlayersInRoomsCount = (int)photonEvent[ParameterCode.PeerCount];
1758 this.mPlayersOnMasterCount = (int)photonEvent[ParameterCode.MasterPeerCount];
1759 this.mGameCount = (int)photonEvent[ParameterCode.GameCount];
1760 break;
1761
1762 case EventCode.Join:
1763 // actorNr is fetched out of event above
1764 Hashtable actorProperties = (Hashtable)photonEvent[ParameterCode.PlayerProperties];
1765 if (originatingPlayer == null)
1766 {
1767 bool isLocal = this.mLocalActor.ID == actorNr;
1768 this.AddNewPlayer(actorNr, new PhotonPlayer(isLocal, actorNr, actorProperties));
1769 this.ResetPhotonViewsOnSerialize(); // This sets the correct OnSerializeState for Reliable OnSerialize
1770 }
1771
1772 if (actorNr == this.mLocalActor.ID)
1773 {
1774 // in this player's 'own' join event, we get a complete list of players in the room, so check if we know all players
1775 int[] actorsInRoom = (int[])photonEvent[ParameterCode.ActorList];
1776 foreach (int actorNrToCheck in actorsInRoom)
1777 {
1778 if (this.mLocalActor.ID != actorNrToCheck && !this.mActors.ContainsKey(actorNrToCheck))
1779 {
1780 this.AddNewPlayer(actorNrToCheck, new PhotonPlayer(false, actorNrToCheck, string.Empty));
1781 }
1782 }
1783
1784 // joinWithCreateOnDemand can turn an OpJoin into creating the room. Then actorNumber is 1 and callback: OnCreatedRoom()
1785 if (this.mLastJoinType == JoinType.JoinOrCreateOnDemand && this.mLocalActor.ID == 1)
1786 {
1787 SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom);
1788 }
1789 SendMonoMessage(PhotonNetworkingMessage.OnJoinedRoom); //Always send OnJoinedRoom
1790
1791 }
1792 else
1793 {
1794 SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerConnected, this.mActors[actorNr]);
1795 }
1796 break;
1797
1798 case EventCode.Leave:
1799 this.HandleEventLeave(actorNr);
1800 break;
1801
1802 case EventCode.PropertiesChanged:
1803 int targetActorNr = (int)photonEvent[ParameterCode.TargetActorNr];
1804 Hashtable gameProperties = null;
1805 Hashtable actorProps = null;
1806 if (targetActorNr == 0)
1807 {
1808 gameProperties = (Hashtable)photonEvent[ParameterCode.Properties];
1809 }
1810 else
1811 {
1812 actorProps = (Hashtable)photonEvent[ParameterCode.Properties];
1813 }
1814
1815 this.ReadoutProperties(gameProperties, actorProps, targetActorNr);
1816 break;
1817
1818 case PunEvent.RPC:
1819 //ts: each event now contains a single RPC. execute this
1820 // Debug.Log("Ev RPC from: " + originatingPlayer);
1821 this.ExecuteRPC(photonEvent[ParameterCode.Data] as Hashtable, originatingPlayer);
1822 break;
1823
1824 case PunEvent.SendSerialize:
1825 case PunEvent.SendSerializeReliable:
1826 Hashtable serializeData = (Hashtable)photonEvent[ParameterCode.Data];
1827 //Debug.Log(serializeData.ToStringFull());
1828
1829 int remoteUpdateServerTimestamp = (int)serializeData[(byte)0];
1830 short remoteLevelPrefix = -1;
1831 short initialDataIndex = 1;
1832 if (serializeData.ContainsKey((byte)1))
1833 {
1834 remoteLevelPrefix = (short)serializeData[(byte)1];
1835 initialDataIndex = 2;
1836 }
1837
1838 for (short s = initialDataIndex; s < serializeData.Count; s++)
1839 {
1840 this.OnSerializeRead(serializeData[s] as Hashtable, originatingPlayer, remoteUpdateServerTimestamp, remoteLevelPrefix);
1841 }
1842 break;
1843
1844 case PunEvent.Instantiation:
1845 this.DoInstantiate((Hashtable)photonEvent[ParameterCode.Data], originatingPlayer, null);
1846 break;
1847
1848 case PunEvent.CloseConnection:
1849 // MasterClient "requests" a disconnection from us
1850 if (originatingPlayer == null || !originatingPlayer.isMasterClient)
1851 {
1852 Debug.LogError("Error: Someone else(" + originatingPlayer + ") then the masterserver requests a disconnect!");
1853 }
1854 else
1855 {
1856 PhotonNetwork.LeaveRoom();
1857 }
1858
1859 break;
1860
1861 case PunEvent.DestroyPlayer:
1862 Hashtable evData = (Hashtable)photonEvent[ParameterCode.Data];
1863 int targetPlayerId = (int)evData[(byte)0];
1864 if (targetPlayerId >= 0)
1865 {
1866 this.DestroyPlayerObjects(targetPlayerId, true);
1867 }
1868 else
1869 {
1870 if (this.DebugOut >= DebugLevel.INFO) Debug.Log("Ev DestroyAll! By PlayerId: " + actorNr);
1871 this.DestroyAll(true);
1872 }
1873 break;
1874
1875 case PunEvent.Destroy:
1876 evData = (Hashtable)photonEvent[ParameterCode.Data];
1877 int instantiationId = (int)evData[(byte)0];
1878 // Debug.Log("Ev Destroy for viewId: " + instantiationId + " sent by owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == actorNr) + " this client is owner: " + (instantiationId / PhotonNetwork.MAX_VIEW_IDS == this.mLocalActor.ID));
1879
1880
1881 PhotonView pvToDestroy = null;
1882 if (this.photonViewList.TryGetValue(instantiationId, out pvToDestroy))
1883 {
1884 this.RemoveInstantiatedGO(pvToDestroy.gameObject, true);
1885 }
1886 else
1887 {
1888 if (this.DebugOut >= DebugLevel.ERROR) Debug.LogError("Ev Destroy Failed. Could not find PhotonView with instantiationId " + instantiationId + ". Sent by actorNr: " + actorNr);
1889 }
1890
1891 break;
1892
1893 case PunEvent.AssignMaster:
1894 evData = (Hashtable)photonEvent[ParameterCode.Data];
1895 int newMaster = (int)evData[(byte)1];
1896 this.SetMasterClient(newMaster, false);
1897 break;
1898
1899 default:
1900 if (photonEvent.Code < 200 && PhotonNetwork.OnEventCall != null)
1901 {
1902 object content = photonEvent[ParameterCode.Data];
1903 PhotonNetwork.OnEventCall(photonEvent.Code, content, actorNr);
1904 }
1905 else
1906 {
1907 // actorNr might be null. it is fetched out of event on top of method
1908 // Hashtable eventContent = (Hashtable) photonEvent[ParameterCode.Data];
1909 // this.mListener.customEventAction(actorNr, eventCode, eventContent);
1910 Debug.LogError("Error. Unhandled event: " + photonEvent);
1911 }
1912 break;
1913 }
1914
1915 this.externalListener.OnEvent(photonEvent);
1916 }
File name: NetworkingPeer.cs
Copy
2279 internal GameObject DoInstantiate(Hashtable evData, PhotonPlayer photonPlayer, GameObject resourceGameObject)
2280 {
2281 // some values always present:
2282 string prefabName = (string)evData[(byte)0];
2283 int serverTime = (int)evData[(byte)6];
2284 int instantiationId = (int)evData[(byte)7];
2285
2286 Vector3 position;
2287 if (evData.ContainsKey((byte)1))
2288 {
2289 position = (Vector3)evData[(byte)1];
2290 }
2291 else
2292 {
2293 position = Vector3.zero;
2294 }
2295
2296 Quaternion rotation = Quaternion.identity;
2297 if (evData.ContainsKey((byte)2))
2298 {
2299 rotation = (Quaternion)evData[(byte)2];
2300 }
2301
2302 int group = 0;
2303 if (evData.ContainsKey((byte)3))
2304 {
2305 group = (int)evData[(byte)3];
2306 }
2307
2308 short objLevelPrefix = 0;
2309 if (evData.ContainsKey((byte)8))
2310 {
2311 objLevelPrefix = (short)evData[(byte)8];
2312 }
2313
2314 int[] viewsIDs;
2315 if (evData.ContainsKey((byte)4))
2316 {
2317 viewsIDs = (int[])evData[(byte)4];
2318 }
2319 else
2320 {
2321 viewsIDs = new int[1] { instantiationId };
2322 }
2323
2324 object[] incomingInstantiationData;
2325 if (evData.ContainsKey((byte)5))
2326 {
2327 incomingInstantiationData = (object[])evData[(byte)5];
2328 }
2329 else
2330 {
2331 incomingInstantiationData = null;
2332 }
2333
2334 // SetReceiving filtering
2335 if (group != 0 && !this.allowedReceivingGroups.Contains(group))
2336 {
2337 return null; // Ignore group
2338 }
2339
2340 // load prefab, if it wasn't loaded before (calling methods might do this)
2341 if (resourceGameObject == null)
2342 {
2343 if (!NetworkingPeer.UsePrefabCache || !NetworkingPeer.PrefabCache.TryGetValue(prefabName, out resourceGameObject))
2344 {
2345 resourceGameObject = (GameObject)Resources.Load(prefabName, typeof(GameObject));
2346 if (NetworkingPeer.UsePrefabCache)
2347 {
2348 NetworkingPeer.PrefabCache.Add(prefabName, resourceGameObject);
2349 }
2350 }
2351
2352 if (resourceGameObject == null)
2353 {
2354 Debug.LogError("PhotonNetwork error: Could not Instantiate the prefab [" + prefabName + "]. Please verify you have this gameobject in a Resources folder.");
2355 return null;
2356 }
2357 }
2358
2359 // now modify the loaded "blueprint" object before it becomes a part of the scene (by instantiating it)
2360 PhotonView[] resourcePVs = resourceGameObject.GetPhotonViewsInChildren();
2361 if (resourcePVs.Length != viewsIDs.Length)
2362 {
2363 throw new Exception("Error in Instantiation! The resource's PhotonView count is not the same as in incoming data.");
2364 }
2365
2366 for (int i = 0; i < viewsIDs.Length; i++)
2367 {
2368 // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below
2369 // so we only set the viewID and instantiationId now. the instantiationData can be fetched
2370 resourcePVs[i].viewID = viewsIDs[i];
2371 resourcePVs[i].prefix = objLevelPrefix;
2372 resourcePVs[i].instantiationId = instantiationId;
2373 resourcePVs[i].isRuntimeInstantiated = true;
2374 }
2375
2376 this.StoreInstantiationData(instantiationId, incomingInstantiationData);
2377
2378 // load the resource and set it's values before instantiating it:
2379 GameObject go = (GameObject)GameObject.Instantiate(resourceGameObject, position, rotation);
2380
2381 for (int i = 0; i < viewsIDs.Length; i++)
2382 {
2383 // NOTE instantiating the loaded resource will keep the viewID but would not copy instantiation data, so it's set below
2384 // so we only set the viewID and instantiationId now. the instantiationData can be fetched
2385 resourcePVs[i].viewID = 0;
2386 resourcePVs[i].prefix = -1;
2387 resourcePVs[i].prefixBackup = -1;
2388 resourcePVs[i].instantiationId = -1;
2389 resourcePVs[i].isRuntimeInstantiated = false;
2390 }
2391
2392 this.RemoveInstantiationData(instantiationId);
2393
2394 // Send OnPhotonInstantiate callback to newly created GO.
2395 // GO will be enabled when instantiated from Prefab and it does not matter if the script is enabled or disabled.
2396 go.SendMessage(PhotonNetworkingMessage.OnPhotonInstantiate.ToString(), new PhotonMessageInfo(photonPlayer, serverTime, null), SendMessageOptions.DontRequireReceiver);
2397 return go;
2398 }
File name: PhotonHandler.cs
Copy
59 protected void Update()
60 {
61 if (PhotonNetwork.networkingPeer == null)
62 {
63 Debug.LogError("NetworkPeer broke!");
64 return;
65 }
66
67 if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated || PhotonNetwork.connectionStateDetailed == PeerState.Disconnected || PhotonNetwork.offlineMode)
68 {
69 return;
70 }
71
72 // the messageQueue might be paused. in that case a thread will send acknowledgements only. nothing else to do here.
73 if (!PhotonNetwork.isMessageQueueRunning)
74 {
75 return;
76 }
77
78 bool doDispatch = true;
79 while (PhotonNetwork.isMessageQueueRunning && doDispatch)
80 {
81 // DispatchIncomingCommands() returns true of it found any command to dispatch (event, result or state change)
82 UnityEngine.Profiling.Profiler.BeginSample("DispatchIncomingCommands");
83 doDispatch = PhotonNetwork.networkingPeer.DispatchIncomingCommands();
84 UnityEngine.Profiling.Profiler.EndSample();
85 }
86
87 int currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000); // avoiding Environment.TickCount, which could be negative on long-running platforms
88 if (PhotonNetwork.isMessageQueueRunning && currentMsSinceStart > this.nextSendTickCountOnSerialize)
89 {
90 PhotonNetwork.networkingPeer.RunViewUpdate();
91 this.nextSendTickCountOnSerialize = currentMsSinceStart + this.updateIntervalOnSerialize;
92 this.nextSendTickCount = 0; // immediately send when synchronization code was running
93 }
94
95 currentMsSinceStart = (int)(Time.realtimeSinceStartup * 1000);
96 if (currentMsSinceStart > this.nextSendTickCount)
97 {
98 bool doSend = true;
99 while (PhotonNetwork.isMessageQueueRunning && doSend)
100 {
101 // Send all outgoing commands
102 UnityEngine.Profiling.Profiler.BeginSample("SendOutgoingCommands");
103 doSend = PhotonNetwork.networkingPeer.SendOutgoingCommands();
104 UnityEngine.Profiling.Profiler.EndSample();
105 }
106
107 this.nextSendTickCount = currentMsSinceStart + this.updateInterval;
108 }
109 }
File name: PhotonLagSimulationGui.cs
Copy
57 private void NetSimWindow(int windowId)
58 {
59 GUILayout.Label(string.Format("Rtt:{0,4} +/-{1,3}", this.Peer.RoundTripTime, this.Peer.RoundTripTimeVariance));
60
61 bool simEnabled = this.Peer.IsSimulationEnabled;
62 bool newSimEnabled = GUILayout.Toggle(simEnabled, "Simulate");
63 if (newSimEnabled != simEnabled)
64 {
65 this.Peer.IsSimulationEnabled = newSimEnabled;
66 }
67
68 float inOutLag = this.Peer.NetworkSimulationSettings.IncomingLag;
69 GUILayout.Label("Lag " + inOutLag);
70 inOutLag = GUILayout.HorizontalSlider(inOutLag, 0, 500);
71
72 this.Peer.NetworkSimulationSettings.IncomingLag = (int)inOutLag;
73 this.Peer.NetworkSimulationSettings.OutgoingLag = (int)inOutLag;
74
75 float inOutJitter = this.Peer.NetworkSimulationSettings.IncomingJitter;
76 GUILayout.Label("Jit " + inOutJitter);
77 inOutJitter = GUILayout.HorizontalSlider(inOutJitter, 0, 100);
78
79 this.Peer.NetworkSimulationSettings.IncomingJitter = (int)inOutJitter;
80 this.Peer.NetworkSimulationSettings.OutgoingJitter = (int)inOutJitter;
81
82 float loss = this.Peer.NetworkSimulationSettings.IncomingLossPercentage;
83 GUILayout.Label("Loss " + loss);
84 loss = GUILayout.HorizontalSlider(loss, 0, 10);
85
86 this.Peer.NetworkSimulationSettings.IncomingLossPercentage = (int)loss;
87 this.Peer.NetworkSimulationSettings.OutgoingLossPercentage = (int)loss;
88
89 // if anything was clicked, the height of this window is likely changed. reduce it to be layouted again next frame
90 if (GUI.changed)
91 {
92 this.WindowRect.height = 100;
93 }
94
95 GUI.DragWindow();
96 }
File name: PhotonNetwork.cs
Copy
1167 /// - Invalid AppId (calls: OnFailedToConnectToPhoton(). check exact AppId value)
1168 /// - Network issues (calls: OnFailedToConnectToPhoton())
1169 /// - Invalid region (calls: OnConnectionFail() with DisconnectCause.InvalidRegion)
1170 /// - Subscription CCU limit reached (calls: OnConnectionFail() with DisconnectCause.MaxCcuReached. also calls: OnPhotonMaxCccuReached())
1179 public static bool ConnectToMaster(string masterServerAddress, int port, string appID, string gameVersion)
1180 {
1181 if (networkingPeer.PeerState != PeerStateValue.Disconnected)
1182 {
1183 Debug.LogWarning("ConnectToMaster() failed. Can only connect while in state 'Disconnected'. Current state: " + networkingPeer.PeerState);
1184 return false;
1185 }
1186
1187 if (offlineMode)
1188 {
1189 offlineMode = false; // Cleanup offline mode
1190 Debug.LogWarning("ConnectToMaster() disabled the offline mode. No longer offline.");
1191 }
1192
1193 if (!isMessageQueueRunning)
1194 {
1195 isMessageQueueRunning = true;
1196 Debug.LogWarning("ConnectToMaster() enabled isMessageQueueRunning. Needs to be able to dispatch incoming messages.");
1197 }
1198
1199 networkingPeer.SetApp(appID, gameVersion);
1200 networkingPeer.IsUsingNameServer = false;
1201 networkingPeer.IsInitialConnect = true;
1202 networkingPeer.MasterServerAddress = (port == 0) ? masterServerAddress : masterServerAddress + ":" + port;
1203
1204 return networkingPeer.Connect(networkingPeer.MasterServerAddress, ServerConnection.MasterServer);
1205 }
File name: PhotonStatsGui.cs
Copy
77 public void TrafficStatsWindow(int windowID)
78 {
79 bool statsToLog = false;
80 TrafficStatsGameLevel gls = PhotonNetwork.networkingPeer.TrafficStatsGameLevel;
81 long elapsedMs = PhotonNetwork.networkingPeer.TrafficStatsElapsedMs / 1000;
82 if (elapsedMs == 0)
83 {
84 elapsedMs = 1;
85 }
86
87 GUILayout.BeginHorizontal();
88 this.buttonsOn = GUILayout.Toggle(this.buttonsOn, "buttons");
89 this.healthStatsVisible = GUILayout.Toggle(this.healthStatsVisible, "health");
90 this.trafficStatsOn = GUILayout.Toggle(this.trafficStatsOn, "traffic");
91 GUILayout.EndHorizontal();
92
93 string total = string.Format("Out|In|Sum:\t{0,4} | {1,4} | {2,4}", gls.TotalOutgoingMessageCount, gls.TotalIncomingMessageCount, gls.TotalMessageCount);
94 string elapsedTime = string.Format("{0}sec average:", elapsedMs);
95 string average = string.Format("Out|In|Sum:\t{0,4} | {1,4} | {2,4}", gls.TotalOutgoingMessageCount / elapsedMs, gls.TotalIncomingMessageCount / elapsedMs, gls.TotalMessageCount / elapsedMs);
96 GUILayout.Label(total);
97 GUILayout.Label(elapsedTime);
98 GUILayout.Label(average);
99
100 if (this.buttonsOn)
101 {
102 GUILayout.BeginHorizontal();
103 this.statsOn = GUILayout.Toggle(this.statsOn, "stats on");
104 if (GUILayout.Button("Reset"))
105 {
106 PhotonNetwork.networkingPeer.TrafficStatsReset();
107 PhotonNetwork.networkingPeer.TrafficStatsEnabled = true;
108 }
109 statsToLog = GUILayout.Button("To Log");
110 GUILayout.EndHorizontal();
111 }
112
113 string trafficStatsIn = string.Empty;
114 string trafficStatsOut = string.Empty;
115 if (this.trafficStatsOn)
116 {
117 trafficStatsIn = "Incoming: " + PhotonNetwork.networkingPeer.TrafficStatsIncoming.ToString();
118 trafficStatsOut = "Outgoing: " + PhotonNetwork.networkingPeer.TrafficStatsOutgoing.ToString();
119 GUILayout.Label(trafficStatsIn);
120 GUILayout.Label(trafficStatsOut);
121 }
122
123 string healthStats = string.Empty;
124 if (this.healthStatsVisible)
125 {
126 healthStats = string.Format(
127 "ping: {6}[+/-{7}]ms\nlongest delta between\nsend: {0,4}ms disp: {1,4}ms\nlongest time for:\nev({3}):{2,3}ms op({5}):{4,3}ms",
128 gls.LongestDeltaBetweenSending,
129 gls.LongestDeltaBetweenDispatching,
130 gls.LongestEventCallback,
131 gls.LongestEventCallbackCode,
132 gls.LongestOpResponseCallback,
133 gls.LongestOpResponseCallbackOpCode,
134 PhotonNetwork.networkingPeer.RoundTripTime,
135 PhotonNetwork.networkingPeer.RoundTripTimeVariance);
136 GUILayout.Label(healthStats);
137 }
138
139 if (statsToLog)
140 {
141 string complete = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}", total, elapsedTime, average, trafficStatsIn, trafficStatsOut, healthStats);
142 Debug.Log(complete);
143 }
144
145 // if anything was clicked, the height of this window is likely changed. reduce it to be layouted again next frame
146 if (GUI.changed)
147 {
148 this.statsRect.height = 100;
149 }
150
151 GUI.DragWindow();
152 }
File name: PickupItem.cs
Copy
74 public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
75 {
76 // read the description in SecondsBeforeRespawn
77
78 if (stream.isWriting && SecondsBeforeRespawn <= 0)
79 {
80 stream.SendNext(this.gameObject.transform.position);
81 }
82 else
83 {
84 // this will directly apply the last received position for this PickupItem. No smoothing. Usually not needed though.
85 Vector3 lastIncomingPos = (Vector3)stream.ReceiveNext();
86 this.gameObject.transform.position = lastIncomingPos;
87 }
88 }
Download file with original file name:Incoming
Incoming 155 lượt xem
Gõ tìm kiếm nhanh...