{"id":80149,"date":"2018-08-01T14:17:58","date_gmt":"2018-08-01T14:17:58","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=80149"},"modified":"2021-07-29T19:44:12","modified_gmt":"2021-07-29T19:44:12","slug":"creating-a-simple-ai-with-unity-and-c","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/creating-a-simple-ai-with-unity-and-c\/","title":{"rendered":"Creating a Simple AI with Unity and C#"},"content":{"rendered":"<p>In any given game, artificial intelligence (AI) is often needed to interact with the user, usually as a force against the player. There are some scenarios where the AI is there to help, and others where it\u2019s both fighting and helping you, but at the end of the day there is some resemblance of intelligence controlled by the computer in games. AI can be made to have simple or complex behaviours, depending on a project&#8217;s requirements. Such requirements may include needing to conduct diplomacy with another player, or just simply walking back and forth on a platform. Whatever it may be, it&#8217;s important to make an AI that does its job well.<\/p>\n<p>In this project, a very simple AI will be demonstrated. Suppose you wanted to make a game where the player must sneak around enemy headquarters. The moment a camera spots the player, enemies can swarm in on the location and give chase to the player for a brief period of time. This project will do exactly that on a basic level. By the time this project is finished, you&#8217;ll have a player object that you can control, a circle that acts as a camera for the enemy, and an enemy object that will give chase to the player once they have been alerted of their presence via the camera object.<\/p>\n<h2>Setting up<\/h2>\n<p>First, you&#8217;ll need to create a 3D project. Start by clicking the <em>New <\/em>button at the top of the window after launching Unity as shown in Figure 1.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1002\" height=\"130\" class=\"wp-image-80150\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 1: Creating a new project<\/p>\n<p>Name your project <em>AI <\/em>and make sure the project is a 3D project. Once you&#8217;ve done that and set a location on your computer for the project, click the <em>Create Project <\/em>button near the bottom shown in Figure 2.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1002\" height=\"579\" class=\"wp-image-80151\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-1.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 2: Project setup screen<\/p>\n<p>With the project created, you&#8217;ll first want to set up some folders in the <em>Assets <\/em>window for the sake of organization. Right click in the <em>Assets <\/em>window and select <em>Create-&gt;Folder <\/em>to create a new folder. Call this folder <em>Materials<\/em>. Then, create a second folder and name it <em>Scripts<\/em>. Figure 3 shows how this should look.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"691\" height=\"679\" class=\"wp-image-80152\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-2.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 3: Creating a new folder<\/p>\n<p>When you&#8217;re done, the <em>Assets <\/em>window should look like the one seen in Figure 4.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"435\" height=\"362\" class=\"wp-image-80153\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-3.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 4: The <em>Assets <\/em>window so far.<\/p>\n<p>Next, create a floor for all the objects to stand upon. In the <em>Hierarchy <\/em>window, select <em>Create-&gt;3D Object-&gt;Plane <\/em>to create a plane object that will act as your floor as shown in Figure 5.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"410\" height=\"371\" class=\"wp-image-80154\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-4.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 5: Creating a plane object.<\/p>\n<p>Name this object <em>Floor <\/em>and give it an <em>X Scale <\/em>of seven and a <em>Z Scale <\/em>of three. Once you&#8217;ve finished that, the <em>Inspector <\/em>window with the <em>Floor <\/em>object selected should look like the one seen in Figure 6.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"606\" height=\"154\" class=\"wp-image-80155\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-5.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 6: Setting <em>Floor <\/em>object properties.<\/p>\n<p>Now you&#8217;ll want to create a new material for the <em>Floor <\/em>to help distinguish it from other objects that will be placed in your scene. Under the <em>Materials <\/em>folder in the <em>Assets <\/em>window, create a new material by right clicking in the <em>Assets <\/em>window and selecting <em>Create-&gt;Material<\/em> shown in Figure 7.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"542\" height=\"642\" class=\"wp-image-80156\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-6.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 7: Creating a new material<\/p>\n<p>Once complete, name the material <em>Floor<\/em> as shown in Figure 8.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"263\" height=\"153\" class=\"wp-image-80157\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-7.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 8: The <em>Floor <\/em>material<\/p>\n<p>Near the top of the <em>Inspector <\/em>window with the <em>Floor <\/em>material selected, select the color picker seen in Figure 9.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"588\" height=\"280\" class=\"wp-image-80158\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-8.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 9: Selecting the color picker.<\/p>\n<p>Of course, the floor can be any color you wish, but in this example it will be set to a brown-red like color as shown in Figure 10.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"293\" height=\"474\" class=\"wp-image-80159\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-9.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 10: The Unity color picker<\/p>\n<p>Select the <em>Floor <\/em>object from the <em>Hierarchy <\/em>window, then under the <em>Mesh Renderer <\/em>component select the small arrow next to <em>Materials<\/em> as shown in Figure 11.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"284\" height=\"116\" class=\"wp-image-80160\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-10.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 11: Preparing to change the material.<\/p>\n<p>Click and drag the <em>Floor <\/em>material from the <em>Assets <\/em>window to the <em>Element 0 <\/em>field under the <em>Mesh Renderer <\/em>component in the <em>Inspector <\/em>window like in Figure 12.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"872\" height=\"232\" class=\"wp-image-80161\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-11.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 12: Setting the <em>Floor <\/em>material as the <em>Floor <\/em>object&#8217;s material<\/p>\n<p>With the <em>Floor <\/em>object finished, you will need to create some walls around the area to prevent the player from falling off the edge. Once again, go to <em>Create-&gt;3D Object-&gt;Plane <\/em>to create a new plane. Name this plane <em>Wall <\/em>and give it the same scale as <em>Floor<\/em>, that being an <em>X Scale <\/em>of 7 and a <em>Z Scale <\/em>of 3. Then, create three more walls by selecting the object and pressing Ctrl + D three times. Once that&#8217;s done, place the walls around the floor using Table 1 as a reference.<\/p>\n<table>\n<tbody>\n<tr>\n<td>\n<p><strong>Name<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Position X<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Position Y<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Position Z<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Rotation X<\/strong><\/p>\n<\/td>\n<td>\n<p><strong>Rotation Z<\/strong><\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>Wall<\/p>\n<\/td>\n<td>\n<p>-35<\/p>\n<\/td>\n<td>\n<p>21<\/p>\n<\/td>\n<td>\n<p>0<\/p>\n<\/td>\n<td>\n<p>0<\/p>\n<\/td>\n<td>\n<p>-90<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>Wall (1)<\/p>\n<\/td>\n<td>\n<p>-1<\/p>\n<\/td>\n<td>\n<p>11<\/p>\n<\/td>\n<td>\n<p>-15<\/p>\n<\/td>\n<td>\n<p>90<\/p>\n<\/td>\n<td>\n<p>0<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>Wall (2)<\/p>\n<\/td>\n<td>\n<p>-1<\/p>\n<\/td>\n<td>\n<p>11<\/p>\n<\/td>\n<td>\n<p>13.5<\/p>\n<\/td>\n<td>\n<p>-90<\/p>\n<\/td>\n<td>\n<p>0<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<p>Wall (3)<\/p>\n<\/td>\n<td>\n<p>34<\/p>\n<\/td>\n<td>\n<p>21<\/p>\n<\/td>\n<td>\n<p>0<\/p>\n<\/td>\n<td>\n<p>0<\/p>\n<\/td>\n<td>\n<p>90<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p class=\"caption\">Table 1: Position and rotations of all <em>Wall <\/em>objects.<\/p>\n<p>In the example images, the walls have been left at their default color. However, if you wish you may give it a new color by creating a new material. Once this is all in place, you should reorient the camera so that it&#8217;s facing down at the floor, in a bird&#8217;s eye view. With the <em>Main Camera<\/em> object selected set its <em>Y Position <\/em>to thirty, <em>Z Position <\/em>to zero, and <em>X Rotation <\/em>to ninety as shown in Figure 13.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"606\" height=\"154\" class=\"wp-image-80162\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-12.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 13: Setting up the camera object.<\/p>\n<p>The scene is now set, so it&#8217;s time to make the player character. In the <em>Hierarchy <\/em>window click <em>Create-&gt;3D Object-&gt;Sphere <\/em>to create a sphere object. Name this object <em>Player<\/em>, then click the <em>Add Component <\/em> button near the bottom of the <em>Inspector <\/em>window with the <em>Player <\/em>object selected as shown in Figure 14.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"450\" height=\"156\" class=\"wp-image-80163\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-13.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 14: Adding a new component.<\/p>\n<p>Now, like in Figure 15, search for <em>Rigidbody<\/em>. Once found, select the <em>Rigidbody <\/em>component from the list to add the <em>Rigidbody <\/em>to the <em>Player<\/em> object.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"450\" height=\"408\" class=\"wp-image-80164\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-14.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 15: Adding a <em>Rigidbody <\/em>component.<\/p>\n<p>Next, you need to assign the player a tag that will come in handy later on in the code. Click the <em>Tag <\/em>drop down menu in the upper left corner of the <em>Inspector <\/em>window and choose the <em>Player <\/em>tag as shown in Figure 16.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"309\" height=\"278\" class=\"wp-image-80165\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-15.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 16: Setting a new tag.<\/p>\n<p>You&#8217;ll need to set a position for the player so it&#8217;s not underneath the <em>Floor<\/em>. The example image places the player in the upper left corner, with an <em>X position<\/em> of 26, <em>Y Position<\/em> of 1, and <em>Z position<\/em> of -9 as shown in Figure 17.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"971\" height=\"558\" class=\"wp-image-80166\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-16.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 17: Positioning the player.<\/p>\n<p>In order for your upcoming code to work properly you&#8217;ll of course need an object to attach it to. Once again, go to the <em>Hierarchy <\/em>window and this time choose <em>Create-&gt;3D Object-&gt;Cube<\/em>. Name this object <em>Guard, <\/em>and add a <em>Rigidbody <\/em>component and a <em>NavMesh Agent <\/em>component using the <em>Add Component <\/em>button in the <em>Inspector<\/em> window. Then, set it somewhere near the upper left corner of the scene. When done, the <em>Inspector <\/em>window for your <em>Guard <\/em>object should look like the one in Figure 18.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"593\" height=\"929\" class=\"wp-image-80167\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-17.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 18: The <em>Guard <\/em>object as seen in the <em>Inspector <\/em>window.<\/p>\n<p>And the object in question should be placed in a similar position to the one seen in Figure 19.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"971\" height=\"558\" class=\"wp-image-80168\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-18.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 19: Positioning the <em>Guard <\/em>object.<\/p>\n<p>Finally you&#8217;ll need an object to act as the <em>Guard <\/em>object&#8217;s &#8220;eyes&#8221; that will alert the <em>Guard <\/em>whenever the player touches it. One last time, go to the <em>Hierarchy <\/em>window and choose <em>Create-&gt;3D Object-&gt;Sphere <\/em>to create another sphere object. Name this object <em>Looker<\/em>. From there you have no other components to add to it at this time. However, you&#8217;ll want to change the size of the object. With <em>Looker <\/em>selected, change the following variables in the <em>Transform <\/em>component under the <em>Inspector <\/em>window.<\/p>\n<ul>\n<li><em>Scale X <\/em>to 9.<\/li>\n<li><em>Scale Y <\/em>to 0.5.<\/li>\n<li><em>Scale Z <\/em>to 9.<\/li>\n<\/ul>\n<p>Once you&#8217;ve done that, position the <em>Looker <\/em>object so it sits in the upper middle part of the floor as shown in Figure 20.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"971\" height=\"558\" class=\"wp-image-80169\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-19.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 20: Positioning the Looker object.<\/p>\n<p>Now is a good time to give <em>Looker <\/em>a unique material to help make it more like something you should avoid. In the <em>Materials <\/em>folder in the <em>Assets <\/em>window, right click and create a new material. Name this one <em>Looker <\/em>and give it a bright red color. Once you&#8217;ve done that set this material as the <em>Looker <\/em>object&#8217;s material to change its color. When finished the scene should now look similar to the one in Figure 21.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"971\" height=\"558\" class=\"wp-image-80170\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-20.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 21: The <em>Looker <\/em>object with the new material attached.<\/p>\n<p>The only task left now is to create a navigation mesh for the <em>Guard <\/em>to navigate with. At the top of the Unity editor lies the <em>Window<\/em> menu. Select <em>Window-&gt;Navigation <\/em>to open the <em>Navigation <\/em>window as shown in Figure 22.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"470\" height=\"748\" class=\"wp-image-80171\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-21.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 22: Opening the <em>Navigation <\/em>window.<\/p>\n<p>Select the <em>Floor <\/em>object in the <em>Hierarchy<\/em>, then in the <em>Navigation <\/em>window select the <em>Navigation Static <\/em>checkbox as shown in Figure 23.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"253\" height=\"136\" class=\"wp-image-80172\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-22.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 23: Setting <em>Navigation Static <\/em>to true.<\/p>\n<p>Next, select the <em>Bake <\/em>option near the top of the window as shown in Figure 24.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"404\" height=\"137\" class=\"wp-image-80173\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-23.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 24: Switiching to the <em>Bake<\/em> menu.<\/p>\n<p>You&#8217;ll be taken to the <em>Bake <\/em>menu where you can edit properties of the navigation mesh you&#8217;re about to create. In this example, there&#8217;s no need to edit anything. All you need to do is click the <em>Bake <\/em>button near the bottom right as shown in Figure 25.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"404\" height=\"233\" class=\"wp-image-80174\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-24.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 25: Creating a new navigation mesh.<\/p>\n<p>At this point, Unity will request that you save your scene. Do so, and then the navigation mesh will be created. Now your scene will look like the one in Figure 26.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"961\" height=\"549\" class=\"wp-image-80175\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-25.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 26: The current scene with the navigation mesh added.<\/p>\n<p>Everything in Unity is now set, so it&#8217;s time to create the scripts needed to make this project work. In the <em>Assets <\/em>window, right click and select <em>Create-&gt;C# Script<\/em> and name this script <em>Player<\/em>. Do this two more times, creating a script named <em>Guard <\/em>and another named <em>Looker<\/em> as shown in Figure 27.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"658\" height=\"625\" class=\"wp-image-80176\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-26.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 27: Creating a new script.<\/p>\n<p>When you&#8217;re done, the <em>Scripts <\/em>folder in the <em>Assets <\/em>window will look like the one in Figure 28.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"443\" height=\"306\" class=\"wp-image-80177\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-27.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 28: The <em>Scripts <\/em>folder.<\/p>\n<p>The <em>Player <\/em>script will be the first script to be coded. Double click the <em>Player <\/em>script in the <em>Assets <\/em>window to open Visual Studio and begin coding!<\/p>\n<h2>The Code<\/h2>\n<p>The <em>Player <\/em>script is fairly simple, as all it\u2019s doing is allowing the user to move the ball object around. Underneath the class declaration, you&#8217;ll need to get a reference to the <em>Rigidbody <\/em>component you created earlier in the project.<\/p>\n<pre class=\"lang:c# theme:vs2012\">private Rigidbody rb;<\/pre>\n<p>Right after that, in the <strong>Start<\/strong> function, you&#8217;ll command Unity to assign the <em>Player <\/em>object&#8217;s current <em>Rigidbody <\/em>component as the value of <em>rb<\/em>.<\/p>\n<pre class=\"lang:c# theme:vs2012\">rb = GetComponent&lt;Rigidbody&gt;();<\/pre>\n<p>With all this done, the <em>Player <\/em>script will look like the one seen in Figure 29.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"365\" height=\"337\" class=\"wp-image-80178\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-28.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 29: The <em>Player <\/em>script so far.<\/p>\n<p>Now that the value of <em>rb <\/em>is assigned, you&#8217;ll need to allow the <em>Player <\/em>object to move whenever any of the arrow keys is pressed. You&#8217;ll be using physics to move the object around, applying force to the object whenever the user presses any of the four arrow keys. To do this, just add the following code to the <em>Update <\/em>function:<\/p>\n<pre class=\"lang:c# theme:vs2012\">if (Input.GetKey(KeyCode.UpArrow))\r\n            rb.AddForce(Vector3.forward * 20);\r\nif (Input.GetKey(KeyCode.DownArrow))\r\n            rb.AddForce(Vector3.back * 20);\r\nif (Input.GetKey(KeyCode.LeftArrow))\r\n            rb.AddForce(Vector3.left * 20);\r\nif (Input.GetKey(KeyCode.RightArrow))\r\n            rb.AddForce(Vector3.right * 20);<\/pre>\n<p>You now have a complete <em>Player <\/em>script. The finished script will look like the one shown in Figure 30.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"395\" height=\"453\" class=\"wp-image-80179\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-29.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 30: The complete <em>Player <\/em>script.<\/p>\n<p>Save your work and go back to Unity. This time, select the <em>Guard <\/em>script from the <em>Assets <\/em>window. In order to make the code for <em>Guard <\/em>work you&#8217;ll need to add a using statement at the top of the script.<\/p>\n<pre class=\"lang:c# theme:vs2012\">using UnityEngine.AI;\r\nNext, declare the following variables just underneath the class declaration.\r\npublic GameObject player;\r\nprivate NavMeshAgent navmesh;<\/pre>\n<p>The <em>Guard <\/em>object will have the <em>Player <\/em>object as the value of the <strong>player<\/strong> variable. This will be needed later when you tell the <em>Guard <\/em>object to pursue the player. Later on, the <strong>navmesh<\/strong> variable is declared to get the object&#8217;s <em>NavMeshAgent <\/em>component. This will be later put to use when the <em>Guard <\/em>pursues the player after they&#8217;ve been alerted of the player touching the <em>Looker <\/em>object. In the <strong>Start<\/strong> function, you&#8217;ll need to set the <em>navmesh <\/em>variable to the object&#8217;s <em>NavMesh Agent <\/em>component by inputting the following:<\/p>\n<pre class=\"lang:c# theme:vs2012\">navmesh = GetComponent&lt;NavMeshAgent&gt;();\r\nThen, in the <em>Update <\/em>function, just add a single line of code:\r\nnavmesh.destination = player.transform.position;<\/pre>\n<p>This line will set a destination point for the <em>Guard <\/em>object. In this case, it will get the <em>Player <\/em>object&#8217;s current position and move towards that point. It will constantly pursue the player once it has been alerted. So now the question is, how does the alert process work? It won&#8217;t be coded in the <em>Guard <\/em>script, but rather in the <em>Looker <\/em>script. Before moving on to the Looker script, take a look at Figure 31 to review your code for the <em>Guard<\/em> script.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"460\" height=\"399\" class=\"wp-image-80180\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-30.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 31: The complete <em>Guard <\/em>script.<\/p>\n<p>Inside <em>Looker, <\/em>you&#8217;ll need to once again declare the following variables.<\/p>\n<pre class=\"lang:c# theme:vs2012\">public GameObject guard;\r\nprivate float reset = 5;\r\nprivate bool movingDown;<\/pre>\n<p>After that, go ahead and comment out the <em>Start <\/em>function as it will not be needed for this script. Jump down to the <em>Update <\/em>function and add the following code:<\/p>\n<pre class=\"lang:c# theme:vs2012\">if (movingDown == false)\r\n            transform.position -= new Vector3(0, 0, 0.1f);\r\n        else\r\n            transform.position += new Vector3(0, 0, 0.1f);\r\nif (transform.position.z &gt; 10)\r\n            movingDown = false;\r\nelse if (transform.position.z &lt; -10)\r\n            movingDown = true;\r\nreset -= Time.deltaTime;\r\nif (reset &lt; 0)\r\n{\r\n            guard.GetComponent&lt;Guard&gt;().enabled = false;\r\n            GetComponent&lt;SphereCollider&gt;().enabled = true;\r\n}<\/pre>\n<p>This is where the bulk of the project&#8217;s action is happening, so let&#8217;s break it down. First, depending on the value of the <strong>movingDown<\/strong> boolean, the object this script is attached to will either be moving up or down. Once it reaches a certain point, it will change direction. Next, the <em>Looker <\/em>will lower the value of reset based on real time. Once that timer is below zero, it will get the <em>Guard <\/em>script on the <em>Guard <\/em>object and disable it, whereupon the <em>Guard <\/em>object will move to the last known player position before that point and then stop moving. <em>Looker <\/em>will also reenable its collider so that the whole process can start again. By this point, the script should look like the one shown in Figure 32.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"476\" height=\"630\" class=\"wp-image-80181\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-31.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 32: The <em>Looker <\/em>script so far.<\/p>\n<p>Speaking of collisions, it&#8217;s time to create the collision code that will reset <em>Looker&#8217;s <\/em>timer and enable the <em>Guard <\/em>script. Underneath the <em>Update <\/em>function, create the following code:<\/p>\n<pre class=\"lang:c# theme:vs2012\">private void OnCollisionEnter(Collision collision)\r\n{\r\n        if (collision.gameObject.tag == \"Player\")\r\n        {\r\n            guard.GetComponent&lt;Guard&gt;().enabled = true;\r\n            reset = 5;\r\n            GetComponent&lt;SphereCollider&gt;().enabled = false;\r\n        }\r\n}<\/pre>\n<p><em>OnCollisionEnter <\/em>is something Unity automatically recognizes as collision code, and thus will execute said code whenever collision with another object occurs. In this case, you first check if the object collided into ha the tag <em>Player<\/em>. If it doesn&#8217;t, it will ignore the rest of the code, like in any other if statement. Otherwise, it will enable the <em>Guard <\/em>script, set the <em>reset <\/em>timer to five (which essentially sets our timer to five seconds), and disable its collider so that the player can still move through the object and not accidentally get stuck on the <em>Looker <\/em>object. The function can be seen in figure 33.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"476\" height=\"180\" class=\"wp-image-80182\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-32.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 33: Collision code for <em>Looker<\/em>.<\/p>\n<p>All the code to make this project is now complete! There&#8217;s a couple other tasks to do before the project is finished. Save all your work and go back to Unity.<\/p>\n<h2>Finishing The Project<\/h2>\n<p>You just need to attach the scripts to their respective objects and assign a few variables to finish the project. First, make sure you switch from the <em>Navigation <\/em>window to the <em>Inspector <\/em>window like in Figure 34.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"476\" height=\"180\" class=\"wp-image-80183\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-33.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 34: Switching to the <em>Inspector <\/em>window.<\/p>\n<p>Once that&#8217;s done, start with the <em>Player <\/em>object. Select it in the <em>Hierarchy <\/em>window, then at the bottom of the <em>Inspector <\/em>window click the <em>Add Component <\/em>button and add the <em>Player <\/em>script. With this added, the <em>Player <\/em>object is complete. Figure 35 shows the added script.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"595\" height=\"203\" class=\"wp-image-80184\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-34.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 35: The <em>Player <\/em>script component.<\/p>\n<p>Next, select the <em>Guard <\/em>object. Like before, attach the <em>Gaurd <\/em>script to the object. This time, you need to let the <em>Guard <\/em>know who the player is. To do this, click and drag the <em>Player <\/em>object from the <em>Hierarchy <\/em>into the the <em>Player <\/em>field in the <em>Guard <\/em>script component as shown in Figure 36.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"925\" height=\"849\" class=\"wp-image-80185\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-35.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 36: Setting the <em>Player <\/em>object as the value of the <em>Player <\/em>field.<\/p>\n<p>You&#8217;ll also want to go ahead and disable the <em>Guard <\/em>script. The way this project is set up, the <em>Guard <\/em>will pursue the player once its script is enabled. This <em>Guard <\/em>script should only be enabled after the player touches the <em>Looker <\/em>object. All you need to do here is simply uncheck the checkbox next to the <em>Guard (Script) <\/em>text in the component as shown in Figure 37.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"234\" height=\"179\" class=\"wp-image-80186\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-36.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 37: Disabling the <em>Guard <\/em>script.<\/p>\n<p>Finally, move on to the <em>Looker <\/em>object and give it the <em>Looker <\/em>script. This time, the <em>Looker <\/em>object will need the <em>Guard <\/em>object as the value of its <em>Guard<\/em> variable. Just like when you assigned the <em>Player <\/em>object to the <em>Guard <\/em>script&#8217;s <em>Player <\/em>variable, you&#8217;ll want to do the same with the <em>Guard <\/em>object and the <em>Looker <\/em>script. Click and drag <em>Guard <\/em>from the <em>Hierarchy <\/em>into the <em>Guard <\/em>field in the <em>Looker <\/em>script component. Once you&#8217;ve done this, the project will be complete! Click the play button at the top of the Unity editor to try out your project as shown in Figure 38.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"254\" height=\"100\" class=\"wp-image-80187\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-37.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 38: Testing the project.<\/p>\n<p>Try moving the <em>Player <\/em>object into the <em>Looker <\/em>object (remember to move with the arrow keys!). Notice that once this is done, the <em>Guard <\/em>object will begin pursuing the player. It will continue its pursuit for about five seconds before giving up chase. Figure 39 shows how the game will look.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1906\" height=\"903\" class=\"wp-image-80188\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2018\/08\/word-image-38.jpeg\" \/><\/p>\n<p class=\"caption\">Figure 39: The complete project in action.<\/p>\n<h2>Conclusion<\/h2>\n<p>This is AI at perhaps its most basic. It can easily be expanded on from here. For example, if we are pretending that the <em>Looker <\/em>object is a camera, a guard is looking through to spot you, then it would be reasonable to assume you could give the <em>Guard <\/em>object its own pair of eyes as well. A player can get past cameras, but they will still need to account for a guard&#8217;s own eyes, adding more to the game. You can also combine this project with the <a href=\"https:\/\/www.red-gate.com\/simple-talk\/dotnet\/c-programming\/pathfinding-unity-c\/\">concept of pathfinding<\/a> to give the guard a path to follow, thus creating a more interesting environment for the player to navigate.<\/p>\n<p>There are many directions you can take with a basic AI like this. Perhaps you don&#8217;t even want to do any of the above and do your own thing. I would encourage you to do just that and experiment with what you have available to you. For all you know, you could come up with an idea for an interesting project that you&#8217;d like to see to completion.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The characters in many games today seem lifelike. Under the covers, an application controls the behavior. In this article, Lance Talbert walks you through setting up a game with some simple artificial intelligence built in using Unity and C#&hellip;<\/p>\n","protected":false},"author":317499,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538],"tags":[],"coauthors":[52549],"class_list":["post-80149","post","type-post","status-publish","format-standard","hentry","category-dotnet-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/80149","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/317499"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=80149"}],"version-history":[{"count":4,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/80149\/revisions"}],"predecessor-version":[{"id":80230,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/80149\/revisions\/80230"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=80149"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=80149"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=80149"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=80149"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}