IEnumerator
How do I use I Enumerator
Below are practical examples compiled from projects for learning and reference purposes
Featured Snippets
File name: NetworkingPeer.cs
Copy
1962 public void ExecuteRPC(Hashtable rpcData, PhotonPlayer sender)
1963 {
1964 if (rpcData == null || !rpcData.ContainsKey((byte)0))
1965 {
1966 Debug.LogError("Malformed RPC; this should never occur. Content: " + SupportClass.DictionaryToString(rpcData));
1967 return;
1968 }
1969
1970 // ts: updated with "flat" event data
1971 int netViewID = (int)rpcData[(byte)0]; // LIMITS PHOTONVIEWS&PLAYERS
1972 int otherSidePrefix = 0; // by default, the prefix is 0 (and this is not being sent)
1973 if (rpcData.ContainsKey((byte)1))
1974 {
1975 otherSidePrefix = (short)rpcData[(byte)1];
1976 }
1977
1978 string inMethodName;
1979 if (rpcData.ContainsKey((byte)5))
1980 {
1981 int rpcIndex = (byte)rpcData[(byte)5]; // LIMITS RPC COUNT
1982 if (rpcIndex > PhotonNetwork.PhotonServerSettings.RpcList.Count - 1)
1983 {
1984 Debug.LogError("Could not find RPC with index: " + rpcIndex + ". Going to ignore! Check PhotonServerSettings.RpcList");
1985 return;
1986 }
1987 else
1988 {
1989 inMethodName = PhotonNetwork.PhotonServerSettings.RpcList[rpcIndex];
1990 }
1991 }
1992 else
1993 {
1994 inMethodName = (string)rpcData[(byte)3];
1995 }
1996
1997 object[] inMethodParameters = null;
1998 if (rpcData.ContainsKey((byte)4))
1999 {
2000 inMethodParameters = (object[])rpcData[(byte)4];
2001 }
2002
2003 if (inMethodParameters == null)
2004 {
2005 inMethodParameters = new object[0];
2006 }
2007
2008 PhotonView photonNetview = this.GetPhotonView(netViewID);
2009 if (photonNetview == null)
2010 {
2011 int viewOwnerId = netViewID/PhotonNetwork.MAX_VIEW_IDS;
2012 bool owningPv = (viewOwnerId == this.mLocalActor.ID);
2013 bool ownerSent = (viewOwnerId == sender.ID);
2014
2015 if (owningPv)
2016 {
2017 Debug.LogWarning("Received RPC \"" + inMethodName + "\" for viewID " + netViewID + " but this PhotonView does not exist! View was/is ours." + (ownerSent ? " Owner called." : " Remote called.") + " By: " + sender.ID);
2018 }
2019 else
2020 {
2021 Debug.LogWarning("Received RPC \"" + inMethodName + "\" for viewID " + netViewID + " but this PhotonView does not exist! Was remote PV." + (ownerSent ? " Owner called." : " Remote called.") + " By: " + sender.ID + " Maybe GO was destroyed but RPC not cleaned up.");
2022 }
2023 return;
2024 }
2025
2026 if (photonNetview.prefix != otherSidePrefix)
2027 {
2028 Debug.LogError(
2029 "Received RPC \"" + inMethodName + "\" on viewID " + netViewID + " with a prefix of " + otherSidePrefix
2030 + ", our prefix is " + photonNetview.prefix + ". The RPC has been ignored.");
2031 return;
2032 }
2033
2034 // Get method name
2035 if (inMethodName == string.Empty)
2036 {
2037 Debug.LogError("Malformed RPC; this should never occur. Content: " + SupportClass.DictionaryToString(rpcData));
2038 return;
2039 }
2040
2041 if (PhotonNetwork.logLevel >= PhotonLogLevel.Full)
2042 Debug.Log("Received RPC: " + inMethodName);
2043
2044
2045 // SetReceiving filtering
2046 if (photonNetview.group != 0 && !allowedReceivingGroups.Contains(photonNetview.group))
2047 {
2048 return; // Ignore group
2049 }
2050
2051 Type[] argTypes = new Type[0];
2052 if (inMethodParameters.Length > 0)
2053 {
2054 argTypes = new Type[inMethodParameters.Length];
2055 int i = 0;
2056 for (int index = 0; index < inMethodParameters.Length; index++)
2057 {
2058 object objX = inMethodParameters[index];
2059 if (objX == null)
2060 {
2061 argTypes[i] = null;
2062 }
2063 else
2064 {
2065 argTypes[i] = objX.GetType();
2066 }
2067
2068 i++;
2069 }
2070 }
2071
2072 int receivers = 0;
2073 int foundMethods = 0;
2074 MonoBehaviour[] mbComponents = photonNetview.GetComponents
2075 for (int componentsIndex = 0; componentsIndex < mbComponents.Length; componentsIndex++)
2076 {
2077 MonoBehaviour monob = mbComponents[componentsIndex];
2078 if (monob == null)
2079 {
2080 Debug.LogError("ERROR You have missing MonoBehaviours on your gameobjects!");
2081 continue;
2082 }
2083
2084 Type type = monob.GetType();
2085
2086 // Get [RPC] methods from cache
2087 List
2088 if (this.monoRPCMethodsCache.ContainsKey(type))
2089 {
2090 cachedRPCMethods = this.monoRPCMethodsCache[type];
2091 }
2092
2093 if (cachedRPCMethods == null)
2094 {
2095 List
2096
2097 this.monoRPCMethodsCache[type] = entries;
2098 cachedRPCMethods = entries;
2099 }
2100
2101 if (cachedRPCMethods == null)
2102 {
2103 continue;
2104 }
2105
2106 // Check cache for valid methodname+arguments
2107 for (int index = 0; index < cachedRPCMethods.Count; index++)
2108 {
2109 MethodInfo mInfo = cachedRPCMethods[index];
2110 if (mInfo.Name == inMethodName)
2111 {
2112 foundMethods++;
2113 ParameterInfo[] pArray = mInfo.GetParameters();
2114 if (pArray.Length == argTypes.Length)
2115 {
2116 // Normal, PhotonNetworkMessage left out
2117 if (this.CheckTypeMatch(pArray, argTypes))
2118 {
2119 receivers++;
2120 object result = mInfo.Invoke((object)monob, inMethodParameters);
2121 if (mInfo.ReturnType == typeof(IEnumerator))
2122 {
2123 monob.StartCoroutine((IEnumerator)result);
2124 }
2125 }
2126 }
2127 else if ((pArray.Length - 1) == argTypes.Length)
2128 {
2129 // Check for PhotonNetworkMessage being the last
2130 if (this.CheckTypeMatch(pArray, argTypes))
2131 {
2132 if (pArray[pArray.Length - 1].ParameterType == typeof(PhotonMessageInfo))
2133 {
2134 receivers++;
2135
2136 int sendTime = (int)rpcData[(byte)2];
2137 object[] deParamsWithInfo = new object[inMethodParameters.Length + 1];
2138 inMethodParameters.CopyTo(deParamsWithInfo, 0);
2139 deParamsWithInfo[deParamsWithInfo.Length - 1] = new PhotonMessageInfo(sender, sendTime, photonNetview);
2140
2141 object result = mInfo.Invoke((object)monob, deParamsWithInfo);
2142 if (mInfo.ReturnType == typeof(IEnumerator))
2143 {
2144 monob.StartCoroutine((IEnumerator)result);
2145 }
2146 }
2147 }
2148 }
2149 else if (pArray.Length == 1 && pArray[0].ParameterType.IsArray)
2150 {
2151 receivers++;
2152 object result = mInfo.Invoke((object)monob, new object[] { inMethodParameters });
2153 if (mInfo.ReturnType == typeof(IEnumerator))
2154 {
2155 monob.StartCoroutine((IEnumerator)result);
2156 }
2157 }
2158 }
2159 }
2160 }
2161
2162 // Error handling
2163 if (receivers != 1)
2164 {
2165 string argsString = string.Empty;
2166 for (int index = 0; index < argTypes.Length; index++)
2167 {
2168 Type ty = argTypes[index];
2169 if (argsString != string.Empty)
2170 {
2171 argsString += ", ";
2172 }
2173
2174 if (ty == null)
2175 {
2176 argsString += "null";
2177 }
2178 else
2179 {
2180 argsString += ty.Name;
2181 }
2182 }
2183
2184 if (receivers == 0)
2185 {
2186 if (foundMethods == 0)
2187 {
2188 Debug.LogError("PhotonView with ID " + netViewID + " has no method \"" + inMethodName + "\" marked with the [RPC](C#) or @RPC(JS) property! Args: " + argsString);
2189 }
2190 else
2191 {
2192 Debug.LogError("PhotonView with ID " + netViewID + " has no method \"" + inMethodName + "\" that takes " + argTypes.Length + " argument(s): " + argsString);
2193 }
2194 }
2195 else
2196 {
2197 Debug.LogError("PhotonView with ID " + netViewID + " has " + receivers + " methods \"" + inMethodName + "\" that takes " + argTypes.Length + " argument(s): " + argsString + ". Should be just one?");
2198 }
2199 }
2200 }
File name: PhotonHandler.cs
Copy
232 internal IEnumerator PingAvailableRegionsCoroutine(bool connectToBest)
233 {
234 BestRegionCodeCurrently = CloudRegionCode.none;
235 while (PhotonNetwork.networkingPeer.AvailableRegions == null)
236 {
237 if (PhotonNetwork.connectionStateDetailed != PeerState.ConnectingToNameServer && PhotonNetwork.connectionStateDetailed != PeerState.ConnectedToNameServer)
238 {
239 Debug.LogError("Call ConnectToNameServer to ping available regions.");
240 yield break; // break if we don't connect to the nameserver at all
241 }
242
243 Debug.Log("Waiting for AvailableRegions. State: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.Server + " PhotonNetwork.networkingPeer.AvailableRegions " + (PhotonNetwork.networkingPeer.AvailableRegions != null));
244 yield return new WaitForSeconds(0.25f); // wait until pinging finished (offline mode won't ping)
245 }
246
247 if (PhotonNetwork.networkingPeer.AvailableRegions == null || PhotonNetwork.networkingPeer.AvailableRegions.Count == 0)
248 {
249 Debug.LogError("No regions available. Are you sure your appid is valid and setup?");
250 yield break; // break if we don't get regions at all
251 }
252
253 //#if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IPHONE)
254 //#pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all)
255 //if (PhotonPeer.NoSocket)
256 //{
257 // if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
258 // {
259 // Debug.Log("PUN disconnects to re-use native sockets for pining servers and to find the best.");
260 // }
261 // PhotonNetwork.Disconnect();
262 //}
263 //#pragma warning restore 0162
264 //#endif
265
266 PhotonPingManager pingManager = new PhotonPingManager();
267 foreach (Region region in PhotonNetwork.networkingPeer.AvailableRegions)
268 {
269 SP.StartCoroutine(pingManager.PingSocket(region));
270 }
271
272 while (!pingManager.Done)
273 {
274 yield return new WaitForSeconds(0.1f); // wait until pinging finished (offline mode won't ping)
275 }
276
277
278 Region best = pingManager.BestRegion;
279 PhotonHandler.BestRegionCodeCurrently = best.Code;
280 PhotonHandler.BestRegionCodeInPreferences = best.Code;
281
282 Debug.Log("Found best region: " + best.Code + " ping: " + best.Ping + ". Calling ConnectToRegionMaster() is: " + connectToBest);
283
284
285 if (connectToBest)
286 {
287 PhotonNetwork.networkingPeer.ConnectToRegionMaster(best.Code);
288 }
289 }
File name: PingCloudRegions.cs
Copy
118 public IEnumerator PingSocket(Region region)
119 {
120 region.Ping = Attempts*MaxMilliseconsPerPing;
121
122 this.PingsRunning++; // TODO: Add try-catch to make sure the PingsRunning are reduced at the end and that the lib does not crash the app
123 PhotonPing ping;
124 //Debug.Log("PhotonHandler.PingImplementation " + PhotonHandler.PingImplementation);
125 if (PhotonHandler.PingImplementation == typeof(PingNativeDynamic))
126 {
127 Debug.Log("Using constructor for new PingNativeDynamic()"); // it seems on android, the Activator can't find the default Constructor
128 ping = new PingNativeDynamic();
129 }
130 else
131 {
132 ping = (PhotonPing)Activator.CreateInstance(PhotonHandler.PingImplementation);
133 }
134
135 //Debug.Log("Ping is: " + ping + " type " + ping.GetType());
136
137 float rttSum = 0.0f;
138 int replyCount = 0;
139
140
141 // PhotonPing.StartPing() requires a plain IP address without port (on all but Windows 8 platforms).
142 // So: remove port and do the DNS-resolving if needed
143 string cleanIpOfRegion = region.HostAndPort;
144 int indexOfColon = cleanIpOfRegion.LastIndexOf(':');
145 if (indexOfColon > 1)
146 {
147 cleanIpOfRegion = cleanIpOfRegion.Substring(0, indexOfColon);
148 }
149 cleanIpOfRegion = ResolveHost(cleanIpOfRegion);
150 //Debug.Log("Resolved and port-less IP is: " + cleanIpOfRegion);
151
152
153 for (int i = 0; i < Attempts; i++)
154 {
155 bool overtime = false;
156 Stopwatch sw = new Stopwatch();
157 sw.Start();
158
159 try
160 {
161 ping.StartPing(cleanIpOfRegion);
162 }
163 catch (Exception e)
164 {
165 Debug.Log("catched: " + e);
166 this.PingsRunning--;
167 break;
168 }
169
170
171 while (!ping.Done())
172 {
173 if (sw.ElapsedMilliseconds >= MaxMilliseconsPerPing)
174 {
175 overtime = true;
176 break;
177 }
178 yield return 0; // keep this loop tight, to avoid adding local lag to rtt.
179 }
180 int rtt = (int)sw.ElapsedMilliseconds;
181
182
183 if (IgnoreInitialAttempt && i == 0)
184 {
185 // do nothing.
186 }
187 else if (ping.Successful && !overtime)
188 {
189 rttSum += rtt;
190 replyCount++;
191 region.Ping = (int)((rttSum) / replyCount);
192 //Debug.Log("region " + region.Code + " RTT " + region.Ping + " success: " + ping.Successful + " over: " + overtime);
193 }
194
195 yield return new WaitForSeconds(0.1f);
196 }
197
198 this.PingsRunning--;
199
200 //Debug.Log("this.PingsRunning: " + this.PingsRunning + " this debug: " + ping.DebugString);
201 yield return null;
202 }
File name: OnClickDestroy.cs
Copy
39 public IEnumerator DestroyRpc()
40 {
41 GameObject.Destroy(this.gameObject);
42 yield return 0; // if you allow 1 frame to pass, the object's OnDestroy() method gets called and cleans up references.
43 PhotonNetwork.UnAllocateViewID(this.photonView.viewID);
44 }
File name: Movable.cs
Copy
32 protected virtual IEnumerator IEMoveBy(Vector3 addPos, Action finishCallback) {
33 ready = false;
34 Vector3 origPos = transform.position;
35 Vector3 targPos = origPos + addPos;
36
37 while (true) {
38 if (IsNear(targPos)) {
39 ready = true;
40 if (finishCallback != null) finishCallback();
41 yield break;
42 }
43 transform.position = Vector3.MoveTowards(transform.position,targPos,speed * Time.deltaTime);
44
45 yield return null;
46 }
47 }
File name: Movable.cs
Copy
49 protected virtual IEnumerator IEMoveToXZ(Node node, Action finishCallback) {
50 ready = false;
51 Vector3 origPos = transform.position;
52 Vector3 targPos = node.transform.position;
53 targPos.y = origPos.y;
54 while (true) {
55 if (IsNear(targPos)) {
56 ready = true;
57 if (finishCallback != null) finishCallback();
58 yield break;
59 }
60 transform.position = Vector3.MoveTowards(transform.position,targPos,speed * Time.deltaTime);
61 yield return null;
62 }
63 }
File name: Scalable.cs
Copy
77 public IEnumerator IEScaleBy(float startAfter, float speed, float scaleBy) {
78 yield return new WaitForSeconds(startAfter);
79
80 float t = Time.deltaTime * speed;
81 float scale = 1f;
82 float diffScale = scaleBy - scale;
83 Vector3 origScale = gameObject.transform.localScale;
84 while(t < Mathf.PI / 2) {
85 t += Time.deltaTime * speed;
86 gameObject.transform.localScale = origScale * (scale + diffScale * Mathf.Sin(t));
87 yield return null;
88 }
89 gameObject.transform.localScale = origScale * scaleBy;
90 }
File name: Scalable.cs
Copy
92 public IEnumerator IEScaleIn(float startAfter, float speed, float endScale) {
93 yield return new WaitForSeconds(startAfter);
94 ready = false;
95 float t = Time.deltaTime * speed;
96 float scale = 1f;
97 while(t < Mathf.PI / 2) {
98 t += Time.deltaTime * speed;
99 scale = endScale * Mathf.Sin(t);
100 transform.localScale = new Vector3(scale,scale,scale);
101 yield return null;
102 }
103 transform.localScale = new Vector3(endScale, endScale, endScale);
104 ready = true;
105 }
File name: Scalable.cs
Copy
107 public IEnumerator IEScaleIn(float startAfter, float speed, Vector3 endScales) {
108 yield return new WaitForSeconds(startAfter);
109 ready = false;
110 float t = Time.deltaTime * speed;
111 float scale = 1f;
112 while(t < Mathf.PI / 2) {
113 t += Time.deltaTime * speed;
114 scale = 1f * Mathf.Sin(t);
115 transform.localScale = endScales * scale;
116 yield return null;
117 }
118 transform.localScale = endScales * scale;
119 ready = true;
120 }
File name: Scalable.cs
Copy
122 public IEnumerator IEScaleOut(float startAfter, float speed) {
123 yield return IEScaleOutBase(startAfter, speed);
124 Destroy(gameObject);
125 }
IEnumerator 130 lượt xem
Gõ tìm kiếm nhanh...