{"id":96988,"date":"2023-06-21T15:46:45","date_gmt":"2023-06-21T15:46:45","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=96988"},"modified":"2023-06-02T19:28:49","modified_gmt":"2023-06-02T19:28:49","slug":"the-essential-unity-classes-to-know","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/other-development\/the-essential-unity-classes-to-know\/","title":{"rendered":"The Essential Unity Classes To Know"},"content":{"rendered":"<p>There are several components that make up the Unity game engine, all of which can become important depending on the project being made in it. Just off the top of one&#8217;s head, there&#8217;s transforms, animators, navigation, shaders, debugging, and the ever-present <code>GameObject<\/code>. And that&#8217;s before you get into any assets you can download to add onto the engine or the more niche elements of Unity. Even those familiar with the engine can risk becoming overwhelmed as they figure out what they need to know to make their project come to life. The necessary knowledge of the Unity game engine will differ depending on one&#8217;s role in the project, and programmers are no exception. In order to assist newcomers to the engine as well as those who need a refresher, we&#8217;ll be covering what is considered by Unity Technologies themselves to be the most important classes coders will likely utilize when creating the scripts for their projects. As we progress, code examples and other illustrations will be used to help demonstrate how a class is used to accomplish goals where applicable.<\/p>\n<h2>GameObject<\/h2>\n<p>For Unity, this class acts as the starting point for the vast majority of objects you code for. It is a base class that represents any object which can appear in a Scene (a Scene being the environment that the user interacts with the app&#8217;s systems in). Whether they be a player avatar, a source of light, or an invisible object that manages data, almost everything in a Unity project begins life as a <code>GameObject<\/code>. This is arguably the one part of Unity that everyone, whether they be programmer, writer, or artist, should have a basic familiarity with. As far as programmers are concerned, the <code>GameObject<\/code> will ultimately be what holds different components based on the object&#8217;s needs, contain variables and references to other objects, and of course, perform operations as defined in custom scripts.<\/p>\n<pre class=\"lang:c# theme:vs2012\">public class GameObjectDemo : MonoBehaviour\r\n{\r\n    \/\/ Start is called before the first frame update\r\n    void Start()\r\n    {\r\n        GameObject myObject = new GameObject();\r\n        myObject.AddComponent&lt;Transform&gt;(); \r\n        myObject.AddComponent&lt;BoxCollider&gt;(); \r\n        myObject.GetComponent&lt;Transform&gt;().localScale = \r\n                                     new Vector3(2, 2, 2);\r\n        Destroy(myObject.GetComponent&lt;BoxCollider&gt;());\r\n        if (myObject.CompareTag(\"myTag\")) \r\n            Debug.Log(\"I have the special tag!\");\r\n        myObject.SetActive(false);                     \r\n        GameObject secondObj = GameObject.Find(\"obj2\"); \r\n        Destroy(secondObj); \r\n    }\r\n}<\/pre>\n<p>Take, for example, the code shown above. We first create a <code>GameObject<\/code>, then give it some components. Depending on its purpose, you may also instantiate the object shortly after this. For this example though, we&#8217;ll get the Transform component using <code>GetComponent<\/code> and set its scale to two, effectively doubling its size, followed by destroying the <code>BoxCollider<\/code> component, once again using <code>GetComponent<\/code> to specify the component we wish to destroy. This is to demonstrate that <code>Destroy<\/code> doesn&#8217;t have to remove entire objects if you don&#8217;t want it to. Moving on from that, we have a check for an object tag. Of course, we won&#8217;t get the <code>Debug.Log<\/code> message since we never assigned a tag to the newly created object in the first place. If it did have the \u201c<code>myTag<\/code>\u201d tag, we could print the special message and, in real world scenarios, perform tasks specific to objects with that tag.<\/p>\n<p>As we wrap up this section, we use <code>SetActive()<\/code> to hide the object from the scene as well as stop any scripts and components attached to the object, including this one. It&#8217;s a handy tool, but caution is needed when using it. You don&#8217;t want to accidentally disable an object without any way to bring it back online later. For the final demonstration, the above code shows off the Find method, which looks for any object with a specified name. In this case, we try searching for an object named <code>\u201cobj2\u201d<\/code>, and assign it as our <code>secondObj<\/code>. And as one final demonstration of the Destroy <code>function<\/code>, we destroy the object we just found.<\/p>\n<h2>MonoBehaviour<\/h2>\n<p>Closely related to the <code>GameObject<\/code> is the <code>MonoBehaviour<\/code> class, which is the default class that Unity scripts derive from. Whenever you create a C# script in Unity, the created class will automatically inherit from the <code>MonoBehaviour<\/code> script. <code>MonoBehaviours<\/code> are what allow you to attach scripts to <code>GameObjects<\/code> as components, and also grants access to methods like Start, <code>FixedUpdate<\/code>, and <code>OnDestroy<\/code>, all of which are regularly used with <code>GameObjects<\/code>. Unless otherwise noted, all the code displayed here is used in scripts that are inheriting from <code>MonoBehaviour<\/code>.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ Start is called before the first frame update\r\nvoid Start()\r\n{\r\n\tmyRigidbody = GetComponent&lt;Rigidbody&gt;();\r\n}\r\n\/\/ Update is called once per frame\r\nvoid Update()\r\n{\r\n\t\/\/ Useful for things that require constant update, \r\n        \/\/like timers or user inputs.\r\n\tmyTimer += Time.deltaTime;\r\n}\r\nvoid FixedUpdate()\r\n{\r\n\t\/\/ use FixedUpdate for physics calculations. \r\n\tmyRigidbody.AddForce(new Vector3(0, 0.1f, 0));\r\n}\r\nvoid LateUpdate()\r\n{\r\n\tif (myTimer &gt; 1.0f)\r\n\t\tmyTimer = 0;\r\n}<\/pre>\n<p>The code above shows the <code>Start<\/code> method as well as all the different types of <code>Update<\/code> methods. Of particular note is the varying <code>Update<\/code> methods, which all work similarly to each other but have some important key differences. Update is run once per frame, meaning any logic you want to execute all the time would go here. A good example of what to do here would be timer control. If you&#8217;re wanting to increment every second, you can do that in <code>Update<\/code> using <code>deltaTime<\/code> like in the code above. <code>FixedUpdate<\/code>, meanwhile, is generally used for physics calculations thanks to its regular call time. It&#8217;s not framerate dependent like Update is, hence, the recommendation for use with physics. Finally, <code>LateUpdate<\/code> is generally used for ordering tasks. It will wait until all the other update functions have executed before performing any tasks specified within <code>LateUpdate<\/code>. It&#8217;s best used for guaranteeing certain tasks are done after all other code has been run.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ OnGUI called when user interacts with GUI, usually for button clicks.\r\nvoid OnGUI()\r\n{\r\n    if (GUI.Button(new Rect(20, 20, 200, 200), \"Click Me!\"))\r\n        buttonClicks++;\r\n}\r\n\/\/ Called when an object is destroyed.\r\nvoid OnDestroy()\r\n{\r\n    Debug.Log(\"Goodbye!\");\r\n}<\/pre>\n<p>Two more <code>Monobehaviour<\/code> methods worth mentioning is <code>OnGUI<\/code> and <code>OnDestroy<\/code>. <code>OnDestroy<\/code> is pretty intuitive, as it simply executes commands once the object is destroyed. It&#8217;s handy for any last minute cleanup you wish to do before an object is removed from the application. <code>OnGUI<\/code> is often used for making quick and easy buttons in an application. Unity does have a UI system that let&#8217;s you create very nice menus, buttons, and more, but if all you want is something really simple and basic then <code>OnGUI<\/code> is a good choice.<\/p>\n<h2>Transform<\/h2>\n<p>One of the more straightforward classes in Unity, the Transform class is responsible for working with a <code>GameObject<\/code>&#8216;s position, rotation, and scale. Whenever you need to update any of these object attributes at runtime, Transform is what you&#8217;ll need to use. These are so important to <code>GameObject<\/code> that Unity does not allow you to remove a <code>GameObject<\/code>&#8216;s <code>Transform<\/code> component. While managing position, rotation, and scale is the <code>Transform<\/code>&#8216;s primary job, it is also used in regards to parent and child relationships in <code>GameObjects<\/code>. Anytime you need to access the parent or child <code>GameObject<\/code>, the <code>Transform<\/code> class will be your gateway to that object.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ Start is called before the first frame update\r\nvoid Start()\r\n{\r\n    myTransform = GetComponent&lt;Transform&gt;();\r\n    Transform childObj = myTransform.GetChild(0); \r\n    Debug.Log(childObj.parent.name); \r\n}\r\n\/\/ Update is called once per frame\r\nvoid Update()\r\n{\r\n    myTransform.Translate(Vector3.right * Time.deltaTime);\r\n    myTransform.Rotate(0.5f, 0.5f, 1, Space.Self); \r\n}<\/pre>\n<p>The code shown above shows everything I just described in action. In the <code>Start<\/code> method we first get this object&#8217;s <code>Transform<\/code> before then finding the object&#8217;s child. We could then use that information later if we wanted to do something with the child object. The code in the <code>Update<\/code> method is a bit simpler, showing an example of moving and rotating an object. Since there&#8217;s no physics involved, it is okay to execute this code once per frame.<\/p>\n<h2>Object<\/h2>\n<p>The base class of <code>GameObject<\/code>, Object is a class for any object Unity can reference in the editor. It is in the <code>UnityEngine<\/code> <code>namepsace<\/code>, and encompasses items like components, materials, text, and more. This is not to be confused with the <code>Object<\/code> class derived from .NET&#8217;s System namespace. Though they share names, they are not at all the same things. That said, you can still use .NET&#8217;s Object class as desired in your C# scripts if you have no interest in the script being assigned to a <code>GameObject<\/code> in the Unity inspector.<\/p>\n<p><code>Object<\/code> brings with it a handful of methods helpful for managing other objects. Of particular usefulness is the <code>Destroy<\/code> and <code>Instantiate<\/code> methods, which is used for deleting and spawning new objects respectively. There&#8217;s also <code>DontDestroyOnLoad<\/code>, which is best used for any objects you want to persist between scenes like game managers. Finally, there&#8217;s the <code>FindObjectOfType<\/code> method and its sibling, <code>FindObjectsOfType<\/code> (note the difference between single and plural <code>\u201cObject\u201d<\/code>). Though slow in performance, these methods are useful for locating specific objects in a scene and doing something with them later. Just be sure you&#8217;re not calling either of these every frame, or prepare to see your project take a hit in performance.<\/p>\n<h2>Debug<\/h2>\n<p>Debugging in Unity is one topic that has been covered here previously. You can read more about that <a href=\"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/debugging-in-unity\/\">here<\/a>. To recap what was said before, the <code>Debug<\/code> class helps you diagnose any issues in your project using console messages, lines, and more. Utilization of <code>Debug<\/code> is inevitable, as it will often be the sole way you&#8217;re able to fully understand a situation you may be presented with. Some helpful tips before moving on \u2013 first, you should know that clicking messages in the Unity console window will highlight the object the message came from, and double clicking will take you to the line of code that generated the message. Second, you can make a distinction between a log, warning, and error message in code to further assist your debugging. Error messages in particular will pause the Unity editor so long as <code>Error<\/code> <code>Pause<\/code> is enabled in your console. Finally, don&#8217;t ignore the <code>DrawLine<\/code> and <code>DrawRay<\/code> methods. In 3D applications specifically, this is a great way to figure out where any raycasts or other lines drawn in the app are located and the direction they&#8217;ve gone.<\/p>\n<h2>Time<\/h2>\n<p>You&#8217;ll likely need to perform some sort of time-related task in your projects such as counting the number of seconds that have passed between one moment and another. The <code>Time<\/code> class is here for scenarios such as this. Closely linked with <code>Time<\/code> is the project&#8217;s FPS (frames per second), which can affect the results of your scripts depending on the exact methods used. For this reason, it will be important to know your target FPS and do your best to maintain that FPS. This will vary based on the device the project runs on and how demanding of said device the project is expected to be. As you&#8217;ll see in the code example below, <code>deltaTime<\/code> is generally what you want to use when tracking time since it returns the time since the last completed frame. This way, you&#8217;ll be able to get consistent results from your code regardless of the FPS.<\/p>\n<pre class=\"lang:c# theme:vs2012\">Time.timeScale = customScale;\r\ntransform.position += Vector3.up * Time.time;\r\n\r\n\/\/ or, you could instead...\r\n\/\/ This is more reliable!\r\ntransform.position += Vector3.up * Time.deltaTime; \r\n<\/pre>\n<p>Our example code is very simple, but there&#8217;s one key difference between the two lines that update position. Moving the position based off <code>Time.time<\/code> results in an object moving according to the number of real-world seconds that has passed since the start of the application. That&#8217;s okay if the project is running flawlessly, but your app running perfectly on every conceivable machine is quite unrealistic. Instead, it&#8217;s better to base it off <code>Time.deltaTime<\/code>, which tracks the time passed based off the last completed frame. In other words, regardless of if your application is running at sixty frames per second or six, the object&#8217;s position will be remain consistent. You won&#8217;t have to worry about an object suddenly teleporting upwards if the application is running slowly.<\/p>\n<h2>Random<\/h2>\n<p>Randomized elements are often useful for giving projects an exciting and suspenseful feel. For instance, if you want to shuffle a deck of cards in a game, you&#8217;ll need to utilize some randomness to make that happen. Thankfully, incorporating those random elements into a project has been made easy thanks to the Random class. Much like <code>Mathf<\/code>, the exact uses for <code>Random<\/code> will vary. Sometimes, you just need a simple random number in a range, at which point the <code>Range<\/code> function will be utilized. But <code>Range<\/code> need not be limited to one number. You can create a random position in your scene using multiple numbers that are randomly generated. Or, if we go back to our earlier example where we needed to shuffle a deck of cards, you can setup a loop that gets a random number in each loop and orders your cards accordingly. If you desire, you can change the seed from which Unity&#8217;s random generation is based upon, or you can simply leave the seed at what Unity itself generates, which is the time at the start of the application.<\/p>\n<p>Executing randomization doesn&#8217;t have to just be about randomizing numbers. You can also get random points in an area, a random rotation, or a random color to name a few. For random points, you have <code>insideUnitCircle<\/code>, <code>insideUnitSphere<\/code>, and <code>onUnitSphere<\/code> functions. The first two simply find a random point in a circle, handy for 2D applications, and finding a random point in a sphere, which is tailored for 3D. <code>onUnitSphere<\/code> is unique in that it finds a random point <em>on top<\/em> of a surface of a sphere. If you take a ball and call <code>onUnitSphere<\/code> and <code>insideUnitSphere<\/code> on it, <code>insideUnitSphere<\/code> will find a spot on the inside of the ball, while <code>onUnitSphere<\/code> will find a random point along the outside of the ball. Depending on your project&#8217;s needs, this can be a very important distinction. Random&#8217;s last two functions are a lot more straightforward, with <code>rotation<\/code> being used to generate a completely random rotation, and <code>ColorHSV<\/code> gets a random color with HSV and alpha values within a certain range. You can even specify the range on <code>ColorHSV<\/code> on as many or as few parameters as you wish. Below are some examples of <em>Random <\/em>in action.<\/p>\n<pre class=\"lang:c# theme:vs2012\">Debug.Log(Random.Range(0, 11)); \/\/ print a number between 0 and 10\r\n\/\/ move somewhere in random point inside sphere.\r\ntransform.position = Random.insideUnitSphere; \r\nsomeColor = Random.ColorHSV(); \/\/ get a random color.<\/pre>\n<h2>Vectors<\/h2>\n<p>You might know Vectors as a mathematics concept that describes things like direction. The same basic logic is applied to the Vector class in Unity, used primarily for items like position of a <code>GameObject<\/code> or the distance between two objects. Vectors can be broken down further into <code>Vector2<\/code>, <code>Vector3<\/code>, and <code>Vector4<\/code> classes, corresponding to 2D, 3D, and 4D vectors respectively. Each of these vectors use many of the same functions, so the information presented here is relevant to all three types. While working in Unity, a <code>Vector<\/code> will most commonly be used alongside <code>Transform<\/code> objects to update an object&#8217;s current position and perform vector arithmetic which can then be used when gathering information like checking a minimum distance between two objects or figuring out an object&#8217;s current direction.<\/p>\n<p>Vectors have several properties and methods that make working with Vectors easier. For starters, Vectors have handy shorthand for moving a direction by one. As an example, Vector2s have <em>down<\/em> (which is like writing <code>Vector2(0,-1)<\/code>), <code>left (Vector2(-1,0))<\/code>, <code>one (Vector2(1,1))<\/code>, and more. <code>Vector3<\/code>s and <code>Vector4<\/code>s have most of these shorthands as well, though the exact word used for each may be a little different. Additionally, you can use <code>Equals<\/code> and <code>Set<\/code> to compare vectors and update existing vectors. There are also methods for finding distance, interpolating between two vectors, calculating angles, and more.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ Start is called before the first frame update\r\nvoid Start()\r\n{\r\n    pos1 = new Vector3(2, 2, 2);\r\n    pos2 = new Vector3(5, 5, 5);\r\n    Debug.Log(Vector3.Distance(pos1, pos2));\r\n}\r\nvoid Update()\r\n{\r\n    if (lerpTime &lt; 1)\r\n    {\r\n        lerpTime += Time.deltaTime * speed; \/\/ set current step\r\n        transform.position = Vector3.Lerp(pos1, pos2, lerpTime);\r\n        \/\/ this does the same thing as the previous line, \r\n        \/\/but with a different method.\r\n        transform.position = Vector3.MoveTowards(pos1, pos2, \r\n                            lerpTime);\r\n    }\r\n}<\/pre>\n<p><code>Lerp<\/code> is perhaps the most frequently used of the <code>Vector<\/code> methods. It&#8217;s used to move an object from some starting position to another ending position gradually over time. The <code>Transform<\/code> section had code that behaved very similarly, but in that case we were simply moving an object to the right forever. With <code>Lerp<\/code>, you have more control over where you move. <code>MoveTowards<\/code> works pretty similarly to <code>Lerp<\/code>, with both serving the same broad purpose. <code>Lerp<\/code> uses the <code>lerpTime<\/code> parameter like a percentage, while <code>MoveTowards<\/code> operates more like a time limit.<\/p>\n<h2>Quaternion<\/h2>\n<p>The <code>Quaternion<\/code> class is another class that works closely with <code>Transform<\/code>, specifically in regards to an object&#8217;s rotation. These are not quite the same as Euler angles, which is what you see displayed in the <code>Inspector<\/code> window in Unity. Euler angles are a <code>Transform<\/code> coordinate which represent the object&#8217;s angle of rotation displayed like a <code>Vector<\/code>. <code>Quaternion<\/code>s are the mathematical notation for this rotation, tracking the rotation as well as direction of the object. While the two work hand in hand, generally you&#8217;ll be converting Euler angles to <code>Quaternion<\/code>s for the purpose of efficiency and stability. It&#8217;s perfectly fine to use Euler angles in your scripts, but it&#8217;s important to eventually convert those to <code>Quaternion<\/code>s somewhere in your code.<\/p>\n<pre class=\"lang:c# theme:vs2012 \">\/\/ Start is called before the first frame update\r\nvoid Start()\r\n{\r\n    Quaternion rotation = Quaternion.LookRotation(lookTarget.position);\r\n    transform.rotation = rotation;\r\n    transform.rotation = Quaternion.Inverse(lookTarget.rotation); \r\n}\r\n\/\/ Update is called once per frame\r\nvoid Update()\r\n{\r\n    if (lerpTime &lt; 1)\r\n    {\r\n        lerpTime += Time.deltaTime * speed;\r\n        transform.rotation = Quaternion.Slerp(transform.rotation, \r\n                                        lookTarget.rotation, lerpTime);\r\n    }\r\n}<\/pre>\n<p>The above code shows two examples of doing the same task but in different ways. Start sees us instantly rotating this object towards another object somewhere in the scene, while Update makes use of <code>Quaternion<\/code>&#8216;s <code>Slerp<\/code> to smoothly rotate the object towards its target over a period of time.<\/p>\n<h2>Mathf<\/h2>\n<p>Of course, it would hardly be programming without some kind of mathematics involved. Unity&#8217;s <code>Mathf<\/code> class provides a helpful collection of common functions you&#8217;re likely to use during development. The functions can be broken down into categories. There are trigonometric functions, like <em>Sin<\/em> and <em>Cos<\/em>. Exponential, square root, and powers form another category, while <em>Log <\/em>and <em>Log10 <\/em>cover the main logarithmic functions. Interpolation functions are available as well, with <code>MoveTowards<\/code> and <code>Lerp<\/code> both seeing regular use in many Unity projects due to their frequent relation to movement related code. Finally, there&#8217;s limiting and repeating functions like <code>Clamp<\/code>, useful for keeping values within a certain range, and <code>Min<\/code> which gives you the lowest between two numbers.<\/p>\n<p>The exact ways you use these math functions will run the gamut. Sometimes, you may make use of them to make simple decisions based off what numbers get returned. Other times, you can use them to help calculate items like in-game power or pricing, while making sure those values don&#8217;t go beyond a certain point. Some use math functions alongside their movement code, while others utilize them to assist with how numbers are displayed on screen. Whatever your goal is, there&#8217;s likely a <code>Mathf<\/code> function that can assist you. With all of them being conveniently called from <code>Mathf<\/code>, it&#8217;s been made easy to incorporate mathematics of all forms into your project. Here&#8217;s a few examples of what you can use the <code>Mathf<\/code> class for:<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ Start is called before the first frame update\r\nvoid Start()\r\n{\r\n    \/\/ Mathf.Sin returns value between -1 and 1.\r\n    displayText.text = Mathf.Sin(angle).ToString();\r\n    \/\/ prints true if power of two.\r\n    Debug.Log(Mathf.IsPowerOfTwo(100));\r\n    \/\/ limit a user's numerical input to 0 and 100, \r\n    \/\/ then display the result.\r\n    someUserInput = Mathf.Clamp(someUserInput, 0, 100);\r\n    Debug.Log(someUserInput);\r\n    \r\n    \/\/ print logarithm of user input.\r\n    Debug.Log(Mathf.Log(someUserInput)); \r\n}\r\n\/\/ Update is called once per frame\r\nvoid Update()\r\n{\r\n    \/\/ animate object moving away from screen using \r\n    \/\/ Mathf.Lerp. \"t\" is number of seconds.\r\n    transform.position = \r\n        new Vector3(0, 0, Mathf.Lerp(minNum, maxNum, t));\r\n    t += Time.deltaTime;\r\n    if (t &gt; 1.0f)\r\n        t = 0;\r\n}<\/pre>\n<h2>ScriptableObject<\/h2>\n<p>Utilizing <code>ScriptableObjects<\/code> has been covered before, so it&#8217;s recommended you check out <a href=\"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/how-to-use-scriptable-objects-in-unity\/\">this article<\/a> if you want more in depth knowledge of the class and how to use it. But in brief, <code>ScriptableObjects<\/code> are data containers meant to hold large amounts of data that&#8217;s independent of individual class instances. As an example, if you have a consumable item such as an apple in your project, you can make an apple <code>ScriptableObject<\/code> which holds the data for the apple (weight, price, etc.), then apply that data to each instance of the apple class. Then, if you decide later you want to adjust the properties of an apple, you can instead update the <code>ScriptableObject<\/code>, thus updating every apple instance in your project all at once. It&#8217;s a handy way to save time in the long run as well as reduce the project&#8217;s memory usage.<\/p>\n<h2>Gizmos<\/h2>\n<p>Allowing the developer to create lines, shapes, and full meshes in the scene view, <code>Gizmos<\/code> are an excellent way to extend your debugging or create visual aids for development. This can be especially helpful for communicating the locations of otherwise \u201cinvisible\u201d objects like light sources or managers. For debugging, you can use it to give additional visual information on anything from collision info to spawn locations. What you do with <code>Gizmos<\/code> is really up to you as the developer. There aren&#8217;t as many methods here as there are in other classes, but what&#8217;s here is clear and easy to understand, thus they are also easy to integrate into your workflow. Here&#8217;s an example of how one can easily create some kind of visual element for an object that is otherwise invisible, such as a trigger area.<\/p>\n<pre class=\"lang:c# theme:vs2012\">private void OnDrawGizmos()\r\n{\r\n\tGizmos.color = Color.blue;\r\n\tGizmos.DrawWireSphere(transform.position, 2f);\r\n}<\/pre>\n<p>That&#8217;s it! The key thing to remember when utilizing gizmos is the <code>OnDrawGizmos<\/code> method. This is how Unity will know to draw a <code>gizmo<\/code> for you at all, so don&#8217;t forget it. Here&#8217;s another example that demonstrates making a <code>gizmo<\/code> which displays a custom icon for the object.<\/p>\n<pre class=\"lang:c# theme:vs2012\">private void OnDrawGizmos()\r\n{\r\n\tGizmos.DrawIcon(transform.position, \"myIcon\"); \r\n}<\/pre>\n<p>This code may look even simpler than the previous example, but there&#8217;s one important catch. For the above code to work, you&#8217;ll need to place your icon in a folder named \u201cGizmos\u201d. The default <code>filepath<\/code> Unity searches for icons is <code>Assets\/Gizmos<\/code>, so not having that folder and placing your icon of choice there will lead to some confusion from Unity. Once you have that set up, you&#8217;ll be able to display any icon you wish for your object.<\/p>\n<h2>Handles<\/h2>\n<p>Complimenting <code>Gizmos<\/code> is the <code>Handles<\/code> class, which focuses more on interaction and manipulation as opposed to <code>Gizmos'<\/code> emphasis on information. The 3D controls that you see in Unity&#8217;s scene window are one such example of a <code>Handle<\/code>. With it you can quickly move, rotate, and scale an object to your heart&#8217;s desire. This and other built-in tools work well, but sometimes you simply need a tool that is tailored to your project. Using <code>Handles<\/code>, you can create your own waypoints, tools for defining \u201csafe\u201d areas in a scene, and much, much more. They&#8217;re a great tool for streamlining your own development or creating helpers to anyone on the development team that&#8217;s not necessarily a programmer. Customizing how the handle looks is also an option, letting you choose which graphic to represent the handle, the color, displaying of text, and the list goes on. There are many options with Handles, too many to thoroughly showcase in this section, but here&#8217;s a few examples gathered into a single script. Given how much is here, comments have been added to the code to clarify what&#8217;s going on as you go.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ the parameters users will be able to change with handles.\r\npublic class HandleDemo : MonoBehaviour\r\n{\r\n    public bool isSpecial;\r\n    public float customNumber = 1f;\r\n}\r\n[CustomEditor(typeof(HandleDemo))]\r\npublic class DrawHandle : Editor\r\n{\r\n    \/\/ display the handle when the object is selected\r\n    private void OnSceneGUI()\r\n    {\r\n        \/\/ get the object this is attached to\r\n        HandleDemo myObj = (HandleDemo)target;\r\n        \/\/ change color depending on boolean value\r\n        if (myObj.isSpecial)\r\n        {\r\n            Handles.color = Color.red;\r\n        }\r\n        else\r\n        {\r\n            Handles.color = Color.yellow;\r\n        }\r\n        \/\/ make handle button, change bool on button click. \r\n        \/\/ Button will appear as wireframe square\r\n        if (Handles.Button(myObj.transform.position + \r\n                new Vector3(2f, 0, 0), myObj.transform.rotation, \r\n                             1f, 1.5f, Handles.RectangleHandleCap))\r\n        {\r\n            myObj.isSpecial = !myObj.isSpecial;\r\n        }\r\n        \/\/ make a label displaying the current value of \r\n        \/\/ customNumber, move it slightly above and to the right \r\n        \/\/ of the object\r\n        Handles.Label(myObj.transform.position + \r\n              new Vector3(0.25f, 1.5f, 0), \r\n                  \"Current value of variable customNumber is: \" + \r\n                                    myObj.customNumber.ToString());\r\n        \/\/ create an arrow shaped scale handle that lets \r\n        \/\/ us change our float variable. Value cannot go lower \r\n        \/\/than 0.25 or higher than 3.\r\n        float newNum = Handles.ScaleValueHandle\r\n           (myObj.customNumber, myObj.transform.position, \r\n           myObj.transform.rotation * \r\n                    Quaternion.Euler(0, -45, 0), 15f, \r\n                            Handles.ArrowHandleCap, 1f);\r\n        if (EditorGUI.EndChangeCheck())\r\n        {\r\n            myObj.customNumber = Mathf.Clamp(newNum, 0.25f, 3);\r\n        }\r\n    }\r\n}<\/pre>\n<p>By including all this, any object that has this code attached as a component will give helpful controls that change the object&#8217;s parameters without having to navigate the Inspector window. You&#8217;ll notice that the file has two classes, one for the object itself and one for the handles. <code>HandleDemo<\/code> inherits from <code>MonoBehaviour<\/code>, and recall that scripts can only be attached to game objects as components if they inherit from that class. But the <em>Handles <\/em>methods used throughout <code>DrawHandle<\/code> asks that we inherit from the Editor class, thus we split them up into separate classes. In order to make the two talk to each other, we first get the object we have selected and inform <code>DrawHandle<\/code> of who it is. Once that information is established, the <code>Handles<\/code> can then take user input through the button or arrow handle that acts as the object&#8217;s controls. It applies that input to the object itself while also updating its own displays based on current values.<\/p>\n<h2>Conclusion<\/h2>\n<p>If you&#8217;re new to Unity, even the most essential of Unity classes can seem like a daunting list to learn. But as the old saying goes, practice makes perfect. This list attempts to order the classes based off what&#8217;s easiest to learn and most important to know for any given project, which should hopefully help any newcomers among us who are interested in using the engine for their projects. Of course, feel free to use this as a quick guide. As for experienced Unity users, one may be surprised at the things they think have figured out, only to discover a whole new way of doing things that&#8217;s far more efficient. For those users, the hope is there&#8217;s still some new knowledge you&#8217;ve obtained here. Whether you&#8217;re a hobbyist or a member of a large team working on a Unity project, these essential classes will likely become useful to you during your project&#8217;s development.<\/p>\n<p>become useful to you during your project&#8217;s development.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are several components that make up the Unity game engine, all of which can become important depending on the project being made in it. Just off the top of one&#8217;s head, there&#8217;s transforms, animators, navigation, shaders, debugging, and the ever-present GameObject. And that&#8217;s before you get into any assets you can download to add&#8230;&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":[53,147591],"tags":[],"coauthors":[52549],"class_list":["post-96988","post","type-post","status-publish","format-standard","hentry","category-featured","category-other-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/96988","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=96988"}],"version-history":[{"count":4,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/96988\/revisions"}],"predecessor-version":[{"id":96991,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/96988\/revisions\/96991"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=96988"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=96988"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=96988"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=96988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}