Sending









How do I use Sending
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: HubGui.cs Copy
28     void OnGUI()
29     {
30         GUI.skin = this.Skin;
31         GUILayout.Space(10);
32
33         GUILayout.BeginHorizontal();
34         GUILayout.Space(10);
35         scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.Width(320));
36
37         GUILayout.Label("Basics", m_Headline);
38         if (GUILayout.Button("Demo Boxes", GUILayout.Width(280)))
39         {
40             demoDescription = "Demo Boxes\n\nUses ConnectAndJoinRandom script.\n(joins a random room or creates one)\n\nInstantiates simple prefab.\nSynchronizes positions without smoothing.";
41             demoBtn = new DemoBtn() { Text = "Start", Link = "DemoBoxes-Scene" };
42         }
43         if (GUILayout.Button("Demo Worker", GUILayout.Width(280)))
44         {
45             demoDescription = "Demo Worker\n\nJoins the default lobby and shows existing rooms.\nLets you create or join a room.\nInstantiates an animated character.\nSynchronizes position and animation state of character with smoothing.\nImplements simple in-room Chat via RPC calls.";
46             demoBtn = new DemoBtn() { Text = "Start", Link = "DemoWorker-Scene" };
47         }
48         if (GUILayout.Button("Movement Smoothing", GUILayout.Width(280)))
49         {
50             demoDescription = "Movement Smoothing\n\nUses ConnectAndJoinRandom script.\nShows several basic ways to update positions of remote objects.";
51             demoBtn = new DemoBtn() { Text = "Start", Link = "DemoSynchronization-Scene" };
52         }
53
54         GUILayout.Label("Advanced", m_Headline);
55         if (GUILayout.Button("Ownership Transfer", GUILayout.Width(280)))
56         {
57             demoDescription = "Ownership Transfer\n\nShows how to transfer the ownership of a PhotonView.\nThe owner will send position updates of the GameObject.\nTransfer can be edited per PhotonView and set to Fixed (no transfer), Request (owner has to agree) or Takeover (owner can't object).";
58             this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoChangeOwner-Scene" };
59             this.webLink = new DemoBtn();
60         }
61         if (GUILayout.Button("Pickup, Teams, Scores", GUILayout.Width(280)))
62         {
63             demoDescription = "Pickup, Teams, Scores\n\nUses ConnectAndJoinRandom script.\nImplements item pickup with RPCs.\nUses Custom Properties for Teams.\nCounts score per player and team.\nUses PhotonPlayer extension methods for easy Custom Property access.";
64             this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoPickup-Scene" };
65             this.webLink = new DemoBtn();
66         }
67
68         GUILayout.Label("Feature Demos", m_Headline);
69         if (GUILayout.Button("Chat", GUILayout.Width(280)))
70         {
71             demoDescription = "Chat\n\nUses the Chat API (now part of PUN).\nSimple UI.\nYou can enter any User ID.\nAutomatically subscribes some channels.\nAllows simple commands via text.\n\nRequires configuration of Chat App ID in scene.";
72             this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoChat-Scene" };
73             this.webLink = new DemoBtn();
74         }
75         if (GUILayout.Button("RPG Movement", GUILayout.Width(280)))
76         {
77             demoDescription = "RPG Movement\n\nDemonstrates how to use the PhotonTransformView component to synchronize position updates smoothly using inter- and extrapolation.\n\nThis demo also shows how to setup a Mecanim Animator to update animations automatically based on received position updates (without sending explicit animation updates).";
78             this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoRPGMovement-Scene" };
79             this.webLink = new DemoBtn();
80         }
81         if (GUILayout.Button("Mecanim Animations", GUILayout.Width(280)))
82         {
83             demoDescription = "Mecanim Animations\n\nThis demo shows how to use the PhotonAnimatorView component to easily synchronize Mecanim animations.\n\nIt also demonstrates another feature of the PhotonTransformView component which gives you more control how position updates are inter-/extrapolated by telling the component how fast the object moves and turns using SetSynchronizedValues().";
84             this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoMecanim-Scene" };
85             this.webLink = new DemoBtn();
86         }
87         if (GUILayout.Button("2D Game", GUILayout.Width(280)))
88         {
89             demoDescription = "2D Game Demo\n\nSynchronizes animations, positions and physics in a 2D scene.";
90             this.demoBtn = new DemoBtn() { Text = "Start", Link = "Demo2DJumpAndRunWithPhysics-Scene" };
91             this.webLink = new DemoBtn();
92         }
93         if (GUILayout.Button("Friends & Authentication", GUILayout.Width(280)))
94         {
95             demoDescription = "Friends & Authentication\n\nShows connect with or without (server-side) authentication.\n\nAuthentication requires minor server-side setup (in Dashboard).\n\nOnce connected, you can find (made up) friends.\nJoin a room just to see how that gets visible in friends list.";
96             this.demoBtn = new DemoBtn() { Text = "Start", Link = "DemoFriends-Scene" };
97             this.webLink = new DemoBtn();
98         }
99
100         GUILayout.Label("Tutorial", m_Headline);
101         if (GUILayout.Button("Marco Polo Tutorial", GUILayout.Width(280)))
102         {
103             demoDescription = "Marco Polo Tutorial\n\nFinal result you could get when you do the Marco Polo Tutorial.\nSlightly modified to be more compatible with this package.";
104             this.demoBtn = new DemoBtn() { Text = "Start", Link = "MarcoPolo-Scene" };
105             this.webLink = new DemoBtn() { Text = "Open Tutorial (www)", Link = "http://tinyurl.com/nmylf44" };
106         }
107         GUILayout.EndScrollView();
108
109         GUILayout.BeginVertical(GUILayout.Width(Screen.width - 345));
110         GUILayout.Label(demoDescription);
111         GUILayout.Space(10);
112         if (!string.IsNullOrEmpty(this.demoBtn.Text))
113         {
114             if (GUILayout.Button(this.demoBtn.Text))
115             {
116                 Application.LoadLevel(this.demoBtn.Link);
117             }
118         }
119         if (!string.IsNullOrEmpty(this.webLink.Text))
120         {
121             if (GUILayout.Button(this.webLink.Text))
122             {
123                 Application.OpenURL(this.webLink.Link);
124             }
125         }
126         GUILayout.EndVertical();
127
128
129         GUILayout.EndHorizontal();
130     }
File name: NetworkingPeer.cs Copy
459     private void LeftRoomCleanup()
460     {
461         bool wasInRoom = mRoomToGetInto != null;
462         // when leaving a room, we clean up depending on that room's settings.
463         bool autoCleanupSettingOfRoom = (this.mRoomToGetInto != null) ? this.mRoomToGetInto.autoCleanUp : PhotonNetwork.autoCleanUpPlayerObjects;
464
465         this.hasSwitchedMC = false;
466         this.mRoomToGetInto = null;
467         this.mActors = new Dictionary();
468         this.mPlayerListCopy = new PhotonPlayer[0];
469         this.mOtherPlayerListCopy = new PhotonPlayer[0];
470         this.mMasterClient = null;
471         this.allowedReceivingGroups = new HashSet();
472         this.blockSendingGroups = new HashSet();
473         this.mGameList = new Dictionary();
474         this.mGameListCopy = new RoomInfo[0];
475         this.isFetchingFriends = false;
476
477         this.ChangeLocalID(-1);
478
479         // Cleanup all network objects (all spawned PhotonViews, local and remote)
480         if (autoCleanupSettingOfRoom)
481         {
482             this.LocalCleanupAnythingInstantiated(true);
483             PhotonNetwork.manuallyAllocatedViewIds = new List(); // filled and easier to replace completely
484         }
485
486         if (wasInRoom)
487         {
488             SendMonoMessage(PhotonNetworkingMessage.OnLeftRoom);
489         }
490     }
File name: NetworkingPeer.cs Copy
986     public virtual bool OpLeave()
987     {
988         if (this.State != global::PeerState.Joined)
989         {
990             Debug.LogWarning("Not sending leave operation. State is not 'Joined': " + this.State);
991             return false;
992         }
993
994         return this.OpCustom((byte)OperationCode.Leave, null, true, 0);
995     }
File name: NetworkingPeer.cs Copy
1918     private void SendVacantViewIds()
1919     {
1920         Debug.Log("SendVacantViewIds()");
1921         List vacantViews = new List();
1922         foreach (PhotonView view in this.photonViewList.Values)
1923         {
1924             if (!view.isOwnerActive)
1925             {
1926                 vacantViews.Add(view.viewID);
1927             }
1928         }
1929
1930         Debug.Log("Sending vacant view IDs. Length: " + vacantViews.Count);
1931         //this.OpRaiseEvent(PunEvent.VacantViewIds, true, vacantViews.ToArray());
1932         this.OpRaiseEvent(PunEvent.VacantViewIds, vacantViews.ToArray(), true, null);
1933     }
File name: NetworkingPeer.cs Copy
2835     internal void RPC(PhotonView view, string methodName, PhotonPlayer player, bool encrypt, params object[] parameters)
2836     {
2837         if (this.blockSendingGroups.Contains(view.group))
2838         {
2839             return; // Block sending on this group
2840         }
2841
2842         if (view.viewID < 1) //TODO: check why 0 should be illegal
2843         {
2844             Debug.LogError("Illegal view ID:" + view.viewID + " method: " + methodName + " GO:" + view.gameObject.name);
2845         }
2846
2847         if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
2848         {
2849             Debug.Log("Sending RPC \"" + methodName + "\" to player[" + player + "]");
2850         }
2851
2852
2853         //ts: changed RPCs to a one-level hashtable as described in internal.txt
2854         Hashtable rpcEvent = new Hashtable();
2855         rpcEvent[(byte)0] = (int)view.viewID; // LIMITS PHOTONVIEWS&PLAYERS
2856         if (view.prefix > 0)
2857         {
2858             rpcEvent[(byte)1] = (short)view.prefix;
2859         }
2860         rpcEvent[(byte)2] = this.ServerTimeInMilliSeconds;
2861
2862         // send name or shortcut (if available)
2863         int shortcut = 0;
2864         if (rpcShortcuts.TryGetValue(methodName, out shortcut))
2865         {
2866             rpcEvent[(byte)5] = (byte)shortcut; // LIMITS RPC COUNT
2867         }
2868         else
2869         {
2870             rpcEvent[(byte)3] = methodName;
2871         }
2872
2873         if (parameters != null && parameters.Length > 0)
2874         {
2875             rpcEvent[(byte) 4] = (object[]) parameters;
2876         }
2877
2878         if (this.mLocalActor == player)
2879         {
2880             this.ExecuteRPC(rpcEvent, player);
2881         }
2882         else
2883         {
2884             RaiseEventOptions options = new RaiseEventOptions() { TargetActors = new int[] { player.ID }, Encrypt = encrypt };
2885             this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2886         }
2887     }
File name: NetworkingPeer.cs Copy
2890     /// (byte)0 -> (int) ViewId (combined from actorNr and actor-unique-id)
2891     /// (byte)1 -> (short) prefix (level)
2895     /// (byte)5 -> (byte) method shortcut (alternative to name)
2899     internal void RPC(PhotonView view, string methodName, PhotonTargets target, bool encrypt, params object[] parameters)
2900     {
2901         if (this.blockSendingGroups.Contains(view.group))
2902         {
2903             return; // Block sending on this group
2904         }
2905
2906         if (view.viewID < 1)
2907         {
2908             Debug.LogError("Illegal view ID:" + view.viewID + " method: " + methodName + " GO:" + view.gameObject.name);
2909         }
2910
2911         if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
2912             Debug.Log("Sending RPC \"" + methodName + "\" to " + target);
2913
2914
2915         //ts: changed RPCs to a one-level hashtable as described in internal.txt
2916         Hashtable rpcEvent = new Hashtable();
2917         rpcEvent[(byte)0] = (int)view.viewID; // LIMITS NETWORKVIEWS&PLAYERS
2918         if (view.prefix > 0)
2919         {
2920             rpcEvent[(byte)1] = (short)view.prefix;
2921         }
2922         rpcEvent[(byte)2] = this.ServerTimeInMilliSeconds;
2923
2924
2925         // send name or shortcut (if available)
2926         int shortcut = 0;
2927         if (rpcShortcuts.TryGetValue(methodName, out shortcut))
2928         {
2929             rpcEvent[(byte)5] = (byte)shortcut; // LIMITS RPC COUNT
2930         }
2931         else
2932         {
2933             rpcEvent[(byte)3] = methodName;
2934         }
2935
2936         if (parameters != null && parameters.Length > 0)
2937         {
2938             rpcEvent[(byte)4] = (object[])parameters;
2939         }
2940
2941         // Check scoping
2942         if (target == PhotonTargets.All)
2943         {
2944             RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group, Encrypt = encrypt };
2945             this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2946
2947             // Execute local
2948             this.ExecuteRPC(rpcEvent, this.mLocalActor);
2949         }
2950         else if (target == PhotonTargets.Others)
2951         {
2952             RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group, Encrypt = encrypt };
2953             this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2954         }
2955         else if (target == PhotonTargets.AllBuffered)
2956         {
2957             RaiseEventOptions options = new RaiseEventOptions() { CachingOption = EventCaching.AddToRoomCache, Encrypt = encrypt };
2958             this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2959
2960             // Execute local
2961             this.ExecuteRPC(rpcEvent, this.mLocalActor);
2962         }
2963         else if (target == PhotonTargets.OthersBuffered)
2964         {
2965             RaiseEventOptions options = new RaiseEventOptions() { CachingOption = EventCaching.AddToRoomCache, Encrypt = encrypt };
2966             this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2967         }
2968         else if (target == PhotonTargets.MasterClient)
2969         {
2970             if (this.mMasterClient == this.mLocalActor)
2971             {
2972                 this.ExecuteRPC(rpcEvent, this.mLocalActor);
2973             }
2974             else
2975             {
2976                 RaiseEventOptions options = new RaiseEventOptions() { Receivers = ReceiverGroup.MasterClient, Encrypt = encrypt };
2977                 this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2978             }
2979         }
2980         else if (target == PhotonTargets.AllViaServer)
2981         {
2982             RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group, Receivers = ReceiverGroup.All, Encrypt = encrypt };
2983             this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2984             if (PhotonNetwork.offlineMode)
2985             {
2986                 this.ExecuteRPC(rpcEvent, this.mLocalActor);
2987             }
2988         }
2989         else if (target == PhotonTargets.AllBufferedViaServer)
2990         {
2991             RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group, Receivers = ReceiverGroup.All, CachingOption = EventCaching.AddToRoomCache, Encrypt = encrypt };
2992             this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options);
2993             if (PhotonNetwork.offlineMode)
2994             {
2995                 this.ExecuteRPC(rpcEvent, this.mLocalActor);
2996             }
2997         }
2998         else
2999         {
3000             Debug.LogError("Unsupported target enum: " + target);
3001         }
3002     }
File name: NetworkingPeer.cs Copy
3083     public void SetSendingEnabled(int group, bool enabled)
3084     {
3085         if (!enabled)
3086         {
3087             this.blockSendingGroups.Add(group); // can be added to HashSet no matter if already in it
3088         }
3089         else
3090         {
3091             this.blockSendingGroups.Remove(group);
3092         }
3093     }
File name: NetworkingPeer.cs Copy
3096     public void SetSendingEnabled(int[] enableGroups, int[] disableGroups)
3097     {
3098         if(enableGroups!=null){
3099             foreach(int i in enableGroups){
3100                 if(this.blockSendingGroups.Contains(i))
3101                     this.blockSendingGroups.Remove(i);
3102             }
3103         }
3104         if(disableGroups!=null){
3105             foreach(int i in disableGroups){
3106                 if(!this.blockSendingGroups.Contains(i))
3107                     this.blockSendingGroups.Add(i);
3108             }
3109         }
3110     }
File name: NetworkingPeer.cs Copy
3147     public void RunViewUpdate()
3148     {
3149         if (!PhotonNetwork.connected || PhotonNetwork.offlineMode)
3150         {
3151             return;
3152         }
3153
3154         if (this.mActors == null ||
3155#if !PHOTON_DEVELOP
3156             this.mActors.Count <= 1
3157#endif
3158             )
3159         {
3160             return; // No need to send OnSerialize messages (these are never buffered anyway)
3161         }
3162
3163         dataPerGroupReliable.Clear();
3164         dataPerGroupUnreliable.Clear();
3165
3166         /* Format of the data hashtable:
3167          * Hasthable dataPergroup*
3168          * [(byte)0] = this.ServerTimeInMilliSeconds;
3169          * OPTIONAL: [(byte)1] = currentLevelPrefix;
3170          * + data
3171          */
3172
3173         foreach (KeyValuePair kvp in this.photonViewList)
3174         {
3175             PhotonView view = kvp.Value;
3176
3177             if (view.synchronization != ViewSynchronization.Off)
3178             {
3179                 // Fetch all sending photonViews
3180                 if (view.isMine)
3181                 {
3182                     #if UNITY_2_6_1 || UNITY_2_6 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
3183                     if (!view.gameObject.active)
3184                     {
3185                         continue; // Only on actives
3186                     }
3187                     #else
3188                     if (!view.gameObject.activeInHierarchy)
3189                     {
3190                         continue; // Only on actives
3191                     }
3192                     #endif
3193
3194                     if (this.blockSendingGroups.Contains(view.group))
3195                     {
3196                         continue; // Block sending on this group
3197                     }
3198
3199                     // Run it trough its OnSerialize
3200                     Hashtable evData = this.OnSerializeWrite(view);
3201                     if (evData == null)
3202                     {
3203                         continue;
3204                     }
3205
3206                     if (view.synchronization == ViewSynchronization.ReliableDeltaCompressed || view.mixedModeIsReliable)
3207                     {
3208                         if (!evData.ContainsKey((byte)1) && !evData.ContainsKey((byte)2))
3209                         {
3210                             // Everything has been removed by compression, nothing to send
3211                         }
3212                         else
3213                         {
3214                             if (!dataPerGroupReliable.ContainsKey(view.group))
3215                             {
3216                                 dataPerGroupReliable[view.group] = new Hashtable();
3217                                 dataPerGroupReliable[view.group][(byte)0] = this.ServerTimeInMilliSeconds;
3218                                 if (currentLevelPrefix >= 0)
3219                                 {
3220                                     dataPerGroupReliable[view.group][(byte)1] = this.currentLevelPrefix;
3221                                 }
3222                             }
3223                             Hashtable groupHashtable = dataPerGroupReliable[view.group];
3224                             groupHashtable.Add((short)groupHashtable.Count, evData);
3225                         }
3226                     }
3227                     else
3228                     {
3229                         if (!dataPerGroupUnreliable.ContainsKey(view.group))
3230                         {
3231                             dataPerGroupUnreliable[view.group] = new Hashtable();
3232                             dataPerGroupUnreliable[view.group][(byte)0] = this.ServerTimeInMilliSeconds;
3233                             if (currentLevelPrefix >= 0)
3234                             {
3235                                 dataPerGroupUnreliable[view.group][(byte)1] = this.currentLevelPrefix;
3236                             }
3237                         }
3238                         Hashtable groupHashtable = dataPerGroupUnreliable[view.group];
3239                         groupHashtable.Add((short)groupHashtable.Count, evData);
3240                     }
3241                 }
3242                 else
3243                 {
3244                     // Debug.Log(" NO OBS on " + view.name + " " + view.owner);
3245                 }
3246             }
3247             else
3248             {
3249             }
3250         }
3251
3252         //Send the messages: every group is send in it's own message and unreliable and reliable are split as well
3253         RaiseEventOptions options = new RaiseEventOptions();
3254
3255#if PHOTON_DEVELOP
3256         options.Receivers = ReceiverGroup.All;
3257#endif
3258
3259         foreach (KeyValuePair kvp in dataPerGroupReliable)
3260         {
3261             options.InterestGroup = (byte)kvp.Key;
3262             this.OpRaiseEvent(PunEvent.SendSerializeReliable, kvp.Value, true, options);
3263         }
3264         foreach (KeyValuePair kvp in dataPerGroupUnreliable)
3265         {
3266             options.InterestGroup = (byte)kvp.Key;
3267             this.OpRaiseEvent(PunEvent.SendSerialize, kvp.Value, false, options);
3268         }
3269     }
File name: PhotonHandler.cs Copy
24     public int updateIntervalOnSerialize; // time [ms] between consecutive RunViewUpdate calls (sending syncs, etc)
35     protected void Awake()
36     {
37         if (SP != null && SP != this && SP.gameObject != null)
38         {
39             GameObject.DestroyImmediate(SP.gameObject);
40         }
41
42         SP = this;
43         DontDestroyOnLoad(this.gameObject);
44
45         this.updateInterval = 1000 / PhotonNetwork.sendRate;
46         this.updateIntervalOnSerialize = 1000 / PhotonNetwork.sendRateOnSerialize;
47
48         PhotonHandler.StartFallbackSendAckThread();
49     }

Sending 121 lượt xem

Gõ tìm kiếm nhanh...