Attempt









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

Featured Snippets


File name: PhotonConverter.cs Copy
18     public static void RunConversion()
19     {
20         //Ask if user has made a backup.
21         int option = EditorUtility.DisplayDialogComplex("Conversion", "Attempt automatic conversion from Unity Networking to Photon Unity Networking \"PUN\"?", "Yes", "No!", "Pick Script Folder");
22         switch (option)
23         {
24             case 0:
25                 break;
26             case 1:
27                 return;
28             case 2:
29                 PickFolderAndConvertScripts();
30                 return;
31             default:
32                 return;
33         }
34
35         //REAAAALY?
36         bool result = EditorUtility.DisplayDialog("Conversion", "Disclaimer: The code conversion feature is quite crude, but should do it's job well (see the sourcecode). A backup is therefore strongly recommended!", "Yes, I've made a backup: GO", "Abort");
37         if (!result)
38         {
39             return;
40         }
41         Output(EditorApplication.timeSinceStartup + " Started conversion of Unity networking -> Photon");
42
43         //Ask to save current scene (optional)
44         EditorApplication.SaveCurrentSceneIfUserWantsTo();
45
46         EditorUtility.DisplayProgressBar("Converting..", "Starting.", 0);
47
48         //Convert NetworkViews to PhotonViews in Project prefabs
49         //Ask the user if we can move all prefabs to a resources folder
50         bool movePrefabs = EditorUtility.DisplayDialog("Conversion", "Can all prefabs that use a PhotonView be moved to a Resources/ folder? You need this if you use Network.Instantiate.", "Yes", "No");
51
52
53         string[] prefabs = Directory.GetFiles("Assets/", "*.prefab", SearchOption.AllDirectories);
54         foreach (string prefab in prefabs)
55         {
56             EditorUtility.DisplayProgressBar("Converting..", "Object:" + prefab, 0.6f);
57
58             Object[] objs = (Object[])AssetDatabase.LoadAllAssetsAtPath(prefab);
59             int converted = 0;
60             foreach (Object obj in objs)
61             {
62                 if (obj != null && obj.GetType() == typeof(GameObject))
63                     converted += ConvertNetworkView(((GameObject)obj).GetComponents(), false);
64             }
65             if (movePrefabs && converted > 0)
66             {
67                 //This prefab needs to be under the root of a Resources folder!
68                 string path = prefab.Replace("\\", "/");
69                 int lastSlash = path.LastIndexOf("/");
70                 int resourcesIndex = path.LastIndexOf("/Resources/");
71                 if (resourcesIndex != lastSlash - 10)
72                 {
73                     if (path.Contains("/Resources/"))
74                     {
75                         Debug.LogWarning("Warning, prefab [" + prefab + "] was already in a resources folder. But has been placed in the root of another one!");
76                     }
77                     //This prefab NEEDS to be placed under a resources folder
78                     string resourcesFolder = path.Substring(0, lastSlash) + "/Resources/";
79                     EnsureFolder(resourcesFolder);
80                     string newPath = resourcesFolder + path.Substring(lastSlash + 1);
81                     string error = AssetDatabase.MoveAsset(prefab, newPath);
82                     if (error != "")
83                         Debug.LogError(error);
84                     Output("Fixed prefab [" + prefab + "] by moving it into a resources folder.");
85                 }
86             }
87         }
88
89         //Convert NetworkViews to PhotonViews in scenes
90         string[] sceneFiles = Directory.GetFiles("Assets/", "*.unity", SearchOption.AllDirectories);
91         foreach (string sceneName in sceneFiles)
92         {
93             EditorApplication.OpenScene(sceneName);
94             EditorUtility.DisplayProgressBar("Converting..", "Scene:" + sceneName, 0.2f);
95
96             int converted2 = ConvertNetworkView((NetworkView[])GameObject.FindObjectsOfType(typeof(NetworkView)), true);
97             if (converted2 > 0)
98             {
99                 //This will correct all prefabs: The prefabs have gotten new components, but the correct ID's were lost in this case
100                 PhotonViewHandler.HierarchyChange(); //TODO: most likely this is triggered on change or on save
101
102                 Output("Replaced " + converted2 + " NetworkViews with PhotonViews in scene: " + sceneName);
103                 EditorApplication.SaveScene(EditorApplication.currentScene);
104             }
105
106         }
107
108         //Convert C#/JS scripts (API stuff)
109         List scripts = GetScriptsInFolder("Assets");
110
111         EditorUtility.DisplayProgressBar("Converting..", "Scripts..", 0.9f);
112         ConvertScripts(scripts);
113
114         Output(EditorApplication.timeSinceStartup + " Completed conversion!");
115         EditorUtility.ClearProgressBar();
116
117         EditorUtility.DisplayDialog("Completed the conversion", "Don't forget to add \"PhotonNetwork.ConnectWithDefaultSettings();\" to connect to the Photon server before using any multiplayer functionality.", "OK");
118     }
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: Enemy.cs Copy
39   protected override void AttemptMove (int xDir, int yDir)
40   {
41    //Check if skipMove is true, if so set it to false and skip this turn.
42    if(skipMove)
43    {
44     skipMove = false;
45     return;
46
47    }
48
49    //Call the AttemptMove function from MovingObject.
50    base.AttemptMove (xDir, yDir);
51
52    //Now that Enemy has moved, set skipMove to true to skip next move.
53    skipMove = true;
54   }
File name: Enemy.cs Copy
58   public void MoveEnemy ()
59   {
60    //Declare variables for X and Y axis move directions, these range from -1 to 1.
61    //These values allow us to choose between the cardinal directions: up, down, left and right.
62    int xDir = 0;
63    int yDir = 0;
64
65    //If the difference in positions is approximately zero (Epsilon) do the following:
66    if(Mathf.Abs (target.position.x - transform.position.x) < float.Epsilon)
67
68     //If the y coordinate of the target's (player) position is greater than the y coordinate of this enemy's position set y direction 1 (to move up). If not, set it to -1 (to move down).
69     yDir = target.position.y > transform.position.y ? 1 : -1;
70
71    //If the difference in positions is not approximately zero (Epsilon) do the following:
72    else
73     //Check if target x position is greater than enemy's x position, if so set x direction to 1 (move right), if not set to -1 (move left).
74     xDir = target.position.x > transform.position.x ? 1 : -1;
75
76    //Call the AttemptMove function and pass in the generic parameter Player, because Enemy is moving and expecting to potentially encounter a Player
77    AttemptMove (xDir, yDir);
78   }
File name: MovingObject.cs Copy
93   protected virtual void AttemptMove (int xDir, int yDir)
95   {
96    //Hit will store whatever our linecast hits when Move is called.
97    RaycastHit2D hit;
98
99    //Set canMove to true if Move was successful, false if failed.
100    bool canMove = Move (xDir, yDir, out hit);
101
102    //Check if nothing was hit by linecast
103    if(hit.transform == null)
104     //If nothing was hit, return and don't execute further code.
105     return;
106
107    //Get a component reference to the component of type T attached to the object that was hit
108    T hitComponent = hit.transform.GetComponent ();
109
110    //If canMove is false and hitComponent is not equal to null, meaning MovingObject is blocked and has hit something it can interact with.
111    if(!canMove && hitComponent != null)
112
113     //Call the OnCantMove function and pass it hitComponent as a parameter.
114     OnCantMove (hitComponent);
115   }
File name: Player.cs Copy
56   private void Update ()
57   {
58    //If it's not the player's turn, exit the function.
59    if(!GameManager.instance.playersTurn) return;
60
61    int horizontal = 0; //Used to store the horizontal move direction.
62    int vertical = 0; //Used to store the vertical move direction.
63
64    //Check if we are running either in the Unity editor or in a standalone build.
65#if UNITY_STANDALONE || UNITY_WEBPLAYER
66
67    //Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction
68    horizontal = (int) (Input.GetAxisRaw ("Horizontal"));
69
70    //Get input from the input manager, round it to an integer and store in vertical to set y axis move direction
71    vertical = (int) (Input.GetAxisRaw ("Vertical"));
72
73    //Check if moving horizontally, if so set vertical to zero.
74    if(horizontal != 0)
75    {
76     vertical = 0;
77    }
78    //Check if we are running on iOS, Android, Windows Phone 8 or Unity iPhone
79#elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
80
81    //Check if Input has registered more than zero touches
82    if (Input.touchCount > 0)
83    {
84     //Store the first touch detected.
85     Touch myTouch = Input.touches[0];
86
87     //Check if the phase of that touch equals Began
88     if (myTouch.phase == TouchPhase.Began)
89     {
90      //If so, set touchOrigin to the position of that touch
91      touchOrigin = myTouch.position;
92     }
93
94     //If the touch phase is not Began, and instead is equal to Ended and the x of touchOrigin is greater or equal to zero:
95     else if (myTouch.phase == TouchPhase.Ended && touchOrigin.x >= 0)
96     {
97      //Set touchEnd to equal the position of this touch
98      Vector2 touchEnd = myTouch.position;
99
100      //Calculate the difference between the beginning and end of the touch on the x axis.
101      float x = touchEnd.x - touchOrigin.x;
102
103      //Calculate the difference between the beginning and end of the touch on the y axis.
104      float y = touchEnd.y - touchOrigin.y;
105
106      //Set touchOrigin.x to -1 so that our else if statement will evaluate false and not repeat immediately.
107      touchOrigin.x = -1;
108
109      //Check if the difference along the x axis is greater than the difference along the y axis.
110      if (Mathf.Abs(x) > Mathf.Abs(y))
111       //If x is greater than zero, set horizontal to 1, otherwise set it to -1
112       horizontal = x > 0 ? 1 : -1;
113      else
114       //If y is greater than zero, set horizontal to 1, otherwise set it to -1
115       vertical = y > 0 ? 1 : -1;
116     }
117    }
118
119#endif //End of mobile platform dependendent compilation section started above with #elif
120    //Check if we have a non-zero value for horizontal or vertical
121    if(horizontal != 0 || vertical != 0)
122    {
123     //Call AttemptMove passing in the generic parameter Wall, since that is what Player may interact with if they encounter one (by attacking it)
124     //Pass in horizontal and vertical as parameters to specify the direction to move Player in.
125     AttemptMove (horizontal, vertical);
126    }
127   }
File name: Player.cs Copy
131   protected override void AttemptMove (int xDir, int yDir)
132   {
133    //Every time player moves, subtract from food points total.
134    food--;
135
136    //Update food text display to reflect current score.
137    foodText.text = "Food: " + food;
138
139    //Call the AttemptMove method of the base class, passing in the component T (in this case Wall) and x and y direction to move.
140    base.AttemptMove (xDir, yDir);
141
142    //Hit allows us to reference the result of the Linecast done in Move.
143    RaycastHit2D hit;
144
145    //If Move returns true, meaning Player was able to move into an empty space.
146    if (Move (xDir, yDir, out hit))
147    {
148     //Call RandomizeSfx of SoundManager to play the move sound, passing in two audio clips to choose from.
149     SoundManager.instance.RandomizeSfx (moveSound1, moveSound2);
150    }
151
152    //Since the player has moved and lost food points, check if the game has ended.
153    CheckIfGameOver ();
154
155    //Set the playersTurn boolean of GameManager to false now that players turn is over.
156    GameManager.instance.playersTurn = false;
157   }

Attempt 102 lượt xem

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