<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anvarjon Yuldashev on Medium]]></title>
        <description><![CDATA[Stories by Anvarjon Yuldashev on Medium]]></description>
        <link>https://medium.com/@yanvar103?source=rss-e9430a9fc615------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5cF8oP83kVh5o1iu</url>
            <title>Stories by Anvarjon Yuldashev on Medium</title>
            <link>https://medium.com/@yanvar103?source=rss-e9430a9fc615------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:20:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yanvar103/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GME 400: UI Development. Part-1]]></title>
            <link>https://medium.com/@yanvar103/gme-400-ui-development-part-1-dd85f0161a7e?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd85f0161a7e</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 14:57:32 GMT</pubDate>
            <atom:updated>2026-11-21T14:57:32.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s create any UI element in the scene, for example, image and 3D object Cube. You see a very big difference between their visual size on scene view and on game view. All elements which are in Canvas(UI elements) are very big on scene view and normal in game view, other elements we see on original scale on every windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avm1Jx8da3DBGnTaPAxBMw.png" /></figure><p>This is normal Unity behavior, not a bug. An Overlay canvas isn’t really part of the 3D world. Unity draws it directly on top of the screen after everything else has rendered. To show it in the Scene view anyway, Unity treats <strong>1 UI pixel as 1 world unit</strong>. So if your game view is 1920×1080, the canvas in the Scene view is 1920 units wide and 1080 units tall.</p><p>Your regular game objects are usually around 1 unit in size (a default cube is 1×1×1). Next to them, the canvas looks enormous, like a giant wall sitting far away from your level.</p><p>So when you work with UI elements you work looking at Game view, while working with other objects you look at scene view.</p><p>Every UI element Unity creates by default on default UI layer. When you first create UI element Unity also creates it’s Canvas and EventSystem.</p><p>If in your project installed new InputSystem package EventSystem will ask you this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*d-UiESPxF5LRIQzFUUQj0A.png" /></figure><p>In this case press Replace and continue working. It replaces legacy InputSystem module with new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*vzY_8mjXtO3HDAsnoRRR0Q.png" /></figure><p>Here now you have common UI Inputs ready, you will attach your own Action Asset and use it.</p><p>If you drag out UI elements out of Canvas in hierarchy they wouldn’t work, to work and visible properly they must by under the canvas. Also all UI elements work under Canvas with hierarchical structure. 1st object in hierarchy will be under all other objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*U8tk4qYvrTrRHyViQKeVlw.png" /></figure><h3>Adding Sprite Sheet into Unity</h3><p><a href="https://www.magnific.com/vectors/ui-sprite-sheet">Ui sprite sheet Vectors - Download Free High-Quality Vectors | Magnific (formerly Freepik)</a></p><p>Here you can find lot’s of free sprites and use them. Choose one of them and import into assets, then set texture type to sprite 2D and UI and apply it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*MED0iaQdJgNpSm7rfRcTZg.png" /></figure><p>Then make sure your 2d sprite package is installed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*j799-lUF0hspKW3CZi7BKg.png" /></figure><p>It helps you to make several sprites by cutting this complex sprite inside Unity Sprite Editor. Set it multiple then open editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*RkZTe1NpuKP0MqE3zJZsUA.png" /></figure><p>Here you can slice in automatic mode, Unity auto detects them and result is good, some times you have to slice manually</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*VxuEvpt3cYxGlkNPXc7cgw.png" /></figure><p>Click apply anu you see every sprite under texture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*JNKLN0rBlVazxYYu6Klo0A.png" /></figure><h3>Creating a Sprite Sheet</h3><p>Creating a spritesheet is mostly about making transparent background separating elements from background. In novadays AI does it right in downloading page or in any image AI without softwares for free. You can also edit it how you want in seconds using AI. So, I’ll skip this part. If you want to do something special with sprite sheets which AI can’t do as you want there are lot’s of ways and tutorials to do it using photoshop or other similar softwares. Keep in mind one thing, you need to have vector variant(EPS file type) to work with. Then you can edit it in any resolution and export as PNG, then import into Unity.</p><h3>Screen Space Overlay, Camera, and World</h3><p>In Canvas we have Render Mode option, let’s see what it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*DpVuyUroWnCV5HwFfa3ysg.png" /></figure><p>The mode decides where the UI lives and how it gets drawn.</p><blockquote>1. Screen Space — Overlay (default)</blockquote><blockquote>The UI is drawn <strong>on top of everything</strong>, after all cameras have rendered. It doesn’t need a camera.</blockquote><blockquote>Resizes automatically with the screen resolution.</blockquote><blockquote>Always appears in front of 3D objects. Nothing in the world can cover it.</blockquote><blockquote>Isn’t affected by camera settings like post-processing, field of view, or camera shake.</blockquote><blockquote>If several Overlay canvases exist, the <strong>Sort Order</strong> field controls which one draws on top.</blockquote><blockquote><strong>Use it for:</strong> standard HUDs, health bars at the screen edge, pause menus, main menus. This covers most games.</blockquote><blockquote>2. Screen Space — Camera</blockquote><blockquote>The canvas is placed a fixed distance in front of a <strong>specific camera</strong> and scaled to fill that camera’s view.</blockquote><blockquote>Assign the camera in <strong>Render Camera</strong>. Set the distance with <strong>Plane Distance</strong>.</blockquote><blockquote>The UI still fills the screen, but it is rendered by the camera. So:</blockquote><blockquote>Camera effects and post-processing apply to it (bloom, blur, color grading).</blockquote><blockquote>Perspective cameras can add slight perspective if you rotate UI elements.</blockquote><blockquote>3D objects closer to the camera than the canvas can appear <strong>in front of</strong> the UI. This is handy for putting 3D models or particles inside a menu.</blockquote><blockquote>If you forget to assign a camera, it acts like Overlay.</blockquote><blockquote><strong>Use it for:</strong> UI that needs post-processing, particle effects mixed with UI, or 3D models displayed in menus, such as a character preview.</blockquote><blockquote>3. World Space</blockquote><blockquote>The canvas becomes a <strong>normal object in the scene</strong>. You position, rotate, and scale it like any GameObject.</blockquote><blockquote>Size is set with the RectTransform’s width/height in units. Usually you set a large width/height in “pixels” and a small scale, such as <strong>0.01</strong>, to get crisp text at a reasonable world size.</blockquote><blockquote>Assign an <strong>Event Camera</strong> so clicks and touches work.</blockquote><blockquote>Can be hidden behind walls and other objects, just like any 3D object.</blockquote><blockquote><strong>Use it for:</strong> floating health bars and names above characters, in-game screens and signs, interactive panels, and almost all <strong>VR/AR UI</strong>, since Screen Space UI doesn’t work well in VR.</blockquote><p>Let’s use 3 of these and see the difference in example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-hJwczCKeP-7iCtssA-nw.png" /></figure><p>Here we got 3 different type canvases, don’t forget to attach MainCamera to Canvas-Camera, there you also can set the distance plane. If we move or rotate the camera we clearly see the difference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*a7F92eYahZz9GrDVIlHygg.png" /></figure><h3>Canvas Scaler</h3><p>The <strong>Canvas Scaler</strong> component controls how big your UI is on different screens. It’s added automatically when you create a Canvas. Without it, a button that looks right on your 1920×1080 monitor could be tiny on a 4K screen or huge on a small phone.</p><h3>1. Constant Pixel Size (default)</h3><p>UI elements stay the <strong>same size in pixels</strong> whatever the resolution.</p><ul><li>A 200×50 button is always 200×50 screen pixels.</li><li>On a high-resolution screen it looks small. On a low-resolution screen it looks large.</li><li><strong>Scale Factor</strong>: multiplies everything by a fixed amount. You can change it from code, for example for a “UI size” option in settings.</li></ul><p><strong>Use it for:</strong> PC tools or games where you control the UI size yourself. It’s rarely the best choice for games that run on many devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*PDWjjXgVbkAiu-Fle_Ib2w.png" /></figure><h3>2. Scale With Screen Size (most common)</h3><p>You design for a <strong>Reference Resolution</strong>, such as 1920×1080. Unity scales the UI up or down so it keeps the same proportions on any screen.</p><ul><li><strong>Reference Resolution</strong>: the resolution you design at. Set your Game view to that size while building the UI.</li><li><strong>Screen Match Mode</strong>: what to do when the screen’s aspect ratio differs from the reference, for example a 20:9 phone vs. a 16:9 reference:</li><li><strong>Match Width Or Height</strong>: blends between matching width and matching height using the <strong>Match</strong> slider:</li><li><strong>0 (Width)</strong>: UI scales with screen width. Good for portrait games.</li><li><strong>1 (Height)</strong>: UI scales with screen height. Good for landscape games.</li><li><strong>0.5</strong>: a balance between the two. A common safe choice.</li><li><strong>Expand</strong>: scales the canvas so the whole reference area always fits on screen. UI never gets cut off, but you may get extra space at the edges.</li><li><strong>Shrink</strong>: scales so the canvas always fills the screen. Nothing is empty, but parts can go off-screen.</li></ul><p><strong>Use it for:</strong> almost all games, especially mobile and anything that runs on multiple resolutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*R5oinfD64V9SNOfaF_HB-g.png" /></figure><h3>3. Constant Physical Size</h3><p>UI keeps the same <strong>real-world size</strong> (millimeters, inches, points) on every device, using the screen’s DPI.</p><ul><li><strong>Physical Unit</strong>: centimeters, millimeters, inches, points, or picas.</li><li><strong>Fallback Screen DPI</strong>: used when the device doesn’t report its DPI.</li><li><strong>Default Sprite DPI</strong>: how many pixels per inch your sprites are treated as.</li></ul><p><strong>Use it for:</strong> cases where physical size matters, such as touch buttons that should always be about finger-sized. Keep in mind that DPI reporting isn’t always reliable on all devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*pbej4YOCH9fHO9CUOy7K-Q.png" /></figure><h3>UI Rect Transform</h3><p>By clicking this button you can edit the size of UI elements in scene</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdAoHIhhUNpatH2EBE8BnQ.png" /></figure><p>They all are placed relative to anchor points on Canvas and here you can change those anchor points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktqfqztc2UFag8zwxeFroQ.png" /></figure><p>Also here by pressing shift and alt keys you can set UI elements own pivot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*koHqm-8BxyyjB4MnT4dKpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NiAx3AjpEO6B0eDCAQADQ.png" /></figure><p>And place them using it’s pivot and canvas anchor in the same time</p><h3>Text and Images</h3><h3>UI Text</h3><p>You can create a text object under the image so in UI it will be in front of image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8ZBWxXYnMM4EMjmk9cOKw.png" /></figure><p>You can also use new fonts just adding them into project folder, let’s download a cartoonish one from dafont.com</p><p><a href="https://www.dafont.com/">DaFont - Download fonts</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryRAJXcYjdPVVZEycTfqww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*T3bEMfr2dLDs2H-4LX6jTQ.png" /></figure><p>I’ll drag TrueType font file. Then select it and create a font asset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*NdACFSAgrRWJxuOJ57kFeg.png" /></figure><p>Then attach it to Font asset option in text object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqZeU-edI5gOX1vTJ8tggw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*t40jN4k8JlmIgx2g05ccSg.png" /></figure><p>Now we got nice UI text element, try to play with other options and text settings on your own.</p><h3>UI Image — Simple/Filled/Sliced/Tiled</h3><p>Let’s create a board image using existing sprites and see what options it has. If you change the color, it overlay the image, not replaces it. To set it original color set the color to white.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*QTQB1GoYgFUMsj6VGx0reg.png" /></figure><p>We have here Image type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*ekehZSrr_btUN3COBivkqA.png" /></figure><p>If you select Sliced it will ask for borders</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*VPkwnZCeTrnKE6GsH3ttOw.png" /></figure><p>In sprite editor if you select corresponding sprite you can see green points, move them to slice the sprite to parts, pay attention to these corners</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Ko4XrI1eQcVOX9tfaJKJWA.png" /></figure><p>Then try to check off Fill center and change Pixels Per Unit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*gROpbHfSQZ04nVTxXXiYNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*2xS7vEmGa4qRWwGZFoIUtg.png" /></figure><p>Here you can see how it changes, you can stretch in/out with preserving corner aspect ratio. If I set to Tiled instead of stretching it repeats the texture within tiles. Here is the difference between them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRERh5bEcPrznv-4Rl7Vhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-94F15kFzPnlZprP148wg.png" /></figure><p>Very usefull options. Alse there is Filled option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1H19jvf1WxKd3zofr18TA.png" /></figure><p>You see it does nothing with border lines, here you can set filling methods and it’s amount, you can use it for health or stamina bars for example.</p><h3>Masking UI Objects</h3><p>Let me show you how to use mask for UI. Dublicate you image and call it Mask and put image under Mask as a child. To Mask called image add component Mask. Make sure that Mask Image is maskable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*vWTIP__jc8a8rZ7GQZy1qQ.png" /></figure><p>then try to move child Image and you see it is visible by Mask Image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*HfTRFKvbqz2TUN9OclJAfg.png" /></figure><p>If you check off Show Mask Graphic in Mask component you can turn off visibility of mask image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*uwFfwxGjBU0Urw_LdJjIlA.png" /></figure><p>You can aslo use rect mask. remove Mask component, and add Rect Mask 2D instead, you also can turn off Image component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mhGzsnPnJ7CwCjzxkEHqQ.png" /></figure><p>You can make rectangle and soft/hard edges and border them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NDAjuhU2R80yna_DDTNDw.png" /></figure><h3>UI Sprites vs 2D Sprites</h3><p>What is the difference between them? If you drag sprites from project folder into scene you get simple 2D sprites, if you create under canvas UI/Image element then attach there the sprite you get UI sprite. It has different components and it’s own UI layer. UI sprite must be under the canvas to be properly shown on the screen.</p><p>Let’s see how to mask 2D sprites. It works different to UI system. Let’s make it visible inside the mask</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*YXlGkbkGBDh7EPZpcPHTFg.png" /></figure><p>Then I’ll add sprite mask component, in it you have to add sprite for mask, let’s add something with different border shape</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*me576MCBi85K6wYxt_qNSg.png" /></figure><p>you can make it visible outside</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Bu_3SIMQ-DF_Nl-MBKj5RA.png" /></figure><p>try it and play with the options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*W4eRJF9nP0GsIbG3khi9IA.png" /></figure><p>2D sprites we use as scene objects.</p><h3>Text Mesh Pro Overview</h3><p>TextMeshPro(TMP) is modified version of Legacy Text, now in latest versions of Unity Text is completely removed, so we use only TMP. It has these options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*NOrtcoyPvZvdLKoJhv4GYg.png" /></figure><p>Most of these are common for all text objects. Here we can set the gradient color, you can also try spacing options, there has also word spacing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TEwamLP848Ag6FsQjHwPw.png" /></figure><p>There also Wrapping, if you enable it when text goes beyond the limits it moves to the next line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZixjOeCWKXREAXSIPG-ow.png" /></figure><p>It also has Overflow option, let’s try Linked one, enable wrapping then set overflow linked and link the copied TMP. If your text gets bigger it will continue inside that linked TMP space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QRBLfDDFE8idLlcM_yVKA.png" /></figure><p>We can also set it’s material and give a texture, let’s use for it TMP/Distance Field shader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*Jbm-LKCwDTFK2xXOV4nIQg.png" /></figure><p>Here we can attach any texture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30QqUTBGsiZdY_Q9fula9Q.png" /></figure><p>You can give also outline, it also can be a texture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsIuSFc5octbcgiPaisSeA.png" /></figure><p>Here you can try also underlay, lighting and glow, go play with options make you text beautiful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yBcP6Ky_g9FMptls5-V6w.png" /></figure><p>To make these options aviable on your imported custom font you have to got to the Windows/TextMeshPro/FontAssetCreator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*VMqtLgh4sb-tuzb7QMr46g.png" /></figure><p>link your font as Source font file and generate Font Atlas then save it to assets. I have already generated it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*OaX6q-CQwVDn4Sp0hTFS7g.png" /></figure><p>This is actually how it looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*IJ3VTgxayieKEck4JRCitg.png" /></figure><p>So here you can change your font style to anything you want</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*UciohArxTzpGOJobMbItGA.png" /></figure><h3>Challenge: Multiple Canvases</h3><p>Let’s make 2 different canvas types: worldSpace and overlay. Attach worldSpace canvas to a character, you can use it to show character name and it will always look at camera. Use overlay canvas for some sort of stat show health bar and etc. This is most common use of multiple canvas technique. So here we got this hierarchy and 2 cavases with these options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*XjoaSVWWvqg-bRcxGN20XA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*FB9DpqtD1U_m7a6OK6b26g.png" /></figure><p>This how it looks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*AvJCp2naY-dwoCuWJisyjw.png" /></figure><p>Now we need to PlayerName to always face the camera, we can do it by typing LookAt script as before in GME 303: Game Logic &amp; Interactions II.</p><p>Or we can use a function which is already built in Unity. It is a LookAt constraint component. We add it to our Canvas_PlayerName, link MainCamera to it and press activate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*Rkj4pQknzbOr4vSV5rDVKw.png" /></figure><p>It might reverse the text direction, in this case all we need to do is rotate text to 180 by y axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*WaLNzQ8w0XvUsw0q4W8Emg.png" /></figure><p>Not it always looks at camera</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*JGlK_YQh5cKl8xWlIvvVsQ.png" /></figure><h3>UI Minimap</h3><p>For this we need any relief image as map, we import it and set it to out map UI image, Canvas is screen overlay, scale with screen size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*A_wiR9-F8x4Bi0nI5FEf9w.png" /></figure><p>Then inside canvas we se this hierarchy with empty Minimap object on top anchored to top left corner, it aslo has width and height of 100. it is a square map and our place is also square, so their ratio must match, in our case it is 1:1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*SAS9nG04uK0FGilScOSy5Q.png" /></figure><p>under it we have MapMask and Player/Enemy images. Map image is under MapMask. I’ll show options of all these elements</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*t0gC3IbwGo1Y-GGF32W2wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*oJrRagaYA_LQYoNIzoUF8g.png" /></figure><p>As you see map image is 2x bigger than MapMask and it cropped by mask, when player moves MapMask moves with it, Player always in the center of the map. When player reaches the plane border, in map Player also reaches map image’s border. Our plane is 200x200</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*h1XLRJeLRTxaRmeA5Q-2dQ.png" /></figure><p>This is Player img which is a black dot on map, enemy is the same, but in red color. So scene is ready, next part is scripting.</p><p>I’ll create a minimap script and attach it to empty MapManager object. So here is the script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class Minimap : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _player;<br>    [SerializeField] private GameObject _enemy;<br>    [SerializeField] private Image _enemyPos;<br>    [SerializeField] private Image _mapPos;<br><br>    private void Update()<br>    {<br>        _mapPos.rectTransform.localPosition = -1f* new Vector3(_player.transform.position.x, _player.transform.position.z, 0); //multiply -1f if it swapped.<br>        _enemyPos.rectTransform.localPosition = new Vector3(_enemy.transform.position.x, _enemy.transform.position.z, 0);<br>    }<br>}</pre><p>Then attach them in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*55hiD-OsQjZZw9U6PC0fHA.png" /></figure><p>I noticed one bug, I need to put enemy_img under Map_img, because it uses under map img local positions. Let’s test it, you can see we are reaching the border as map also moves to border</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*Y8ND0lu8ujJwW69e5bK0KA.png" /></figure><p>Enemy img also moves properly in map. This is a simple minimap setup that you can use in games.</p><h3>Design a Main Menu</h3><p>First let’s create some typical main menu visual from existing images, using UI sprites and TMP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_tJy9gFmN8OmylTE-CbZg.png" /></figure><p>This is how I did it, don’t forget to set canvas as overlay and screen size scale, reference resolution I did 1920x1080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*TQGjZrcL1NxDxCmanm0YPw.png" /></figure><h3>Buttons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*Km1harghUlKExdOCl7m_SA.png" /></figure><p>Here how we add UI buttons and if you added it you can see it has these settings and components by default, so we see it has Image, Button and other standart UI components, under it we see it has text(TMP) child object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*RzQUnq3Ud0xApzA_Dide5w.png" /></figure><p>Main thing is button component and it’s parameters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*iu8rbRWs7eTk8jbRGU2Wug.png" /></figure><p>You can see at the bottom it has On Click list, here we can add public methods from scripts, wich are going to be called when we press this button. Let’s try it with a simple example. We create empty ButtonManager with it’s script and add a simple public method.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class ButtonManager : MonoBehaviour<br>{<br>    public void ButtonPressed()<br>    {<br>        Debug.Log(&quot;This button is pressed!&quot;);<br>    }<br>}</pre><p>then we add it to button On Click() list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*7UCg-6QfA5ocSpSCWSaVKg.png" /></figure><p>you can test it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*JqfrDSIRF4k2o0WqiJ_9DA.png" /></figure><h3>Virtual Piano</h3><p>Let’s make piano keys. First we need a piano button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*_w8uk1Bt2v6ZTAOdI3vftQ.png" /></figure><p>Then we need an audioScript, we attach it to our button, in it we define these variables first</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*gHpeqJjIlJolunxDDBiIfg.png" /></figure><p>I downloaded a free piano key sound, also we need to add an audio component to button, then we attach everything</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*YD9tsxmGZYxGiNJWZ5dsyA.png" /></figure><p>Next we need an audioMixer. Then open audioMixer window, in it create a Piano group under Master group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKwr6qF5KjisvTy5gbyGfw.png" /></figure><p>Then we create a method which is going to be called when button is pressed, then we add it to button’s On Click() list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*lSuJztiqHV-PCt4NhU9s7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*hOJW2CuGNMhADgxy1HHsTw.png" /></figure><p>As other keys we copy this button and only modify pitch value: 0.8, 0.9, 1.1, 1.2, …</p><p>Then place them nearby in order, now you have a virtual piano keys</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*ZNa3EVm2dEyuDmfPGIeCpA.png" /></figure><p>You can improve audio parameters in audio mixer. Let’s not stray from the topic. You can explore it by yourself later.</p><h3>Selecting Buttons and First Selected</h3><p>Let’s figure out which button color is for what?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*AWPwD-czmBRoIRGtfT2ELg.png" /></figure><p>Let’s try green for highlighted and blue for selected, select all buttons and change them at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*ZGqWjZZtUy1O_nUDuHTZvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*1RLLYT4_rgLdf4Cp1uTKGg.png" /></figure><p>Test it in play mode and see the result. We are using mouse to highlight or select, what if we use only keyboard, in this case we need to add first selected in event system. I’ll attach there our first button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*FGhGfeOYb9Luxe7M28pjEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*eMg3eidn0aeND4snqwYHEA.png" /></figure><p>Now it automatically selected and I can select others by pressing arrow keys.</p><h3>Button Navigation</h3><p>In button component options we have navigation automatic by default</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*7Xel6ih9Se-A0f-mueDilQ.png" /></figure><p>If you press Visualize in Scene view you can see arrows which Unity intelligently draws and determines the button sequence. When you move them it updates in realtime</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YUhriXn5Jw45JijUUKPW7A.png" /></figure><p>In most cases automatic is good, but if you want something specific here you have other options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*cNvFjCrV6eORlDi0H5NJbg.png" /></figure><p>You can try them. In most games you can see selection with loop. We can make it using explicit option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*k4WCyjBHKht2kucep789vA.png" /></figure><p>For example for button 1 we set these</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*2YsHTKhB9qbN0xOOO0Rg6w.png" /></figure><p>for button2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*RV1sbL7aTUQM6CIOibeJYw.png" /></figure><p>for button3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*yk6sJXgIoU-PjL060QUpgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*HuSkLWFmN28AlkV2Kkuyvw.png" /></figure><p>Then get these up/down loop selecting.</p><h3>Button Sprite Swap</h3><p>In button settings instead of using colors we can use custom sprites to make them look visually better, for these we need different prepared sprite variants for different button cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*kxdRmzGzvZZx90dxRVDsuw.png" /></figure><p>All you need is to attach existing sprite images here.</p><h3>Button Animation</h3><p>You can select any UI element and add a parent to it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*yES2fyjWVk2QXCIRy_m-8A.png" /></figure><p>I add an empty parent as position</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*onK6YfLIypij421mUUobHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*qLTaEWfB9b4AoSIw1tR_gg.png" /></figure><p>Then we select animation transition and press Auto Generate Animation, choose path and Unity auto generates default animator component for buttons</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*gmX1aOkGp0Ids_MnQ2wHnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*HxFOybEt_Uar61LHyLK9Ig.png" /></figure><p>Unity already prepared most using states for you, so you can create them and start using in one click. Now let’s try to animate something here. Select the button and open animation window, choose one state, let’s try highlighted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*wPs816kRyuq2GggaHcCPNQ.png" /></figure><p>Press Record button and change the scale to 1.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*S8TSlLcSTXOkmldsyjxNbQ.png" /></figure><p>Stop recording and test it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*bJvq9jzi7uUYOvPEye1vSw.png" /></figure><p>I can add other animation by scaling or using other parameters, I also can make it as prefab and start using for other buttons adjusting only it’s sprite</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*olvYWUU9PcT6C7_yhJP8Uw.png" /></figure><p>So we see Unity made to work with buttons very fast and comfortable.</p><h3>Challenge: UI Menu with No Mouse</h3><p>In real projects we always have multiple menus and lot’s of submenus. When you press one menu button it swithches to next submenu with another menu buttons. The first main menu navigation and defining first selected we already know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIazuKfKE0-vn5OCiaOMig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*TkmAZ7mqtRSZ7L5-YKA35A.png" /></figure><p>Now let’s create a new sub menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdPB9nS2PIr0SEBsPQNk5A.png" /></figure><p>Now to swtich between them and manage visibility we need to create a new script MenuManager</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class MenuManager : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _mainMenu;<br>    [SerializeField] private GameObject _subMenu1;<br>    [SerializeField] private Button _button1; //first selected button in submenu1<br>    <br>    void Start()<br>    {<br>        _mainMenu.SetActive(true);<br>        _subMenu1.SetActive(false);<br>    }<br><br>    public void ButtonPressed()<br>    {<br>        _mainMenu.SetActive(false);<br>        _subMenu1.SetActive(true);<br>        _button1.Select();<br>    }<br>}</pre><p>attach required items</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*8UccY_eJPO_9EIufPg8I4A.png" /></figure><p>then we set button1 on click to show submenu1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*Nt70FalaFMy4pDPRlmH5Fw.png" /></figure><p>This is how we can manage multiple menus.</p><h3>Challenge: Cannon</h3><p>As a challenge we have a turret and 3 UI buttons: step rotate left/right buttons and a fire button. We need to manage a connection between turret and buttons to make turret control by these buttons.</p><p>So let’s prepare the turret first. I downloaded imported this model and creted cube floor and inside turret object created empty InstantiatePoint and sphere as a projectile(with rigidbody) inside it. then made this sphere as a prefab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uPsIuzfOqhVXZ8CQi5OSA.png" /></figure><p>Then we can delete projectile from scene, it will be instantiated from script, we need a new script Turret, also don’t forget attach it to turret parent object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*vop643eQTaotGLfVFN5d0w.png" /></figure><p>Now first better to test it, for this I’ll use legacy input because it is quicker.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class Turret : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _projectile;<br>    [SerializeField] private Transform _instantiatePoint;<br><br>    void Update()<br>    {<br>        if(Input.GetKeyDown(KeyCode.Space))<br>        {<br>            GameObject projectile = Instantiate(_projectile, _instantiatePoint.position, _instantiatePoint.rotation);<br>            projectile.GetComponent&lt;Rigidbody&gt;().AddRelativeForce(new Vector3(0,0,500));<br>        }<br>    }<br>}</pre><p>I tested it shooting projectile as we want. Also easyly we can add rotating</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dFuA7SOimesU4rgSMacdpw.png" /></figure><p>Once our Turret functionality is done it’s time to set up our UI buttons. If we want them to animate by transform(position, rotattion or scale) we need also an empty transform parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Q9v1Gzaa_mehy5TyINYSw.png" /></figure><p>I made a new animated button prefab for it, so if I want to modify the animation it affects all buttons in scene which inherits this prefab. You can animate them as you want by transform, color, make loop animations etc.</p><p>Let’s connect them to our Turret script and modify this script to be suiteble to UI buttons</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class Turret : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _projectile;<br>    [SerializeField] private Transform _instantiatePoint;<br>    [SerializeField] private float _speed = 20f;<br><br>    public void PressFire()<br>    {<br>        GameObject projectile = Instantiate(_projectile, _instantiatePoint.position, _instantiatePoint.rotation);<br>        projectile.GetComponent&lt;Rigidbody&gt;().AddRelativeForce(new Vector3(0, 0, 500));<br>    }<br><br>    public void PressLeft()<br>    {<br>        transform.Rotate(0, 1f * _speed, 0);<br>    }<br><br>    public void PressRight()<br>    {<br>        transform.Rotate(0, -1f * _speed, 0);<br>    }<br>}</pre><p>For each button set it’s own on click function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*_mHy3WNU94IKm8grLnPo0A.png" /></figure><p>Now we got UI button turret control, also you can add up/down rotate buttons and functionToggle Buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*N98qoBT8t80yQD0owYlKlw.png" /></figure><h3>Toggle Buttons</h3><p>Toggle is a on/off switchable UI element, if you create a UI Toggle you can see it has this default structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjNnrJHN2AqB_j7R5iRQ3Q.png" /></figure><p>You can change visual parameters sprites as you want, it is the same as in buttons. Let’s see the Toggle functionality. Let’s create a script and see how it works. But don’t name the script Toggle, in that case Unity replaces it’s own UnityEngine.UI.Toggle with your’s. So name it for example SimpleToggle or MyToggle. If you want to name it exactly Toggle in definition variable you need to need to type</p><pre>[SerializeField] private UnityEngine.UI.Toggle _toggle;<br>//not [SerializeField] private Toggle _toggle;</pre><p>Here is a simple script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class SimpleToggle : MonoBehaviour<br>{<br>    [SerializeField] private Toggle _toggle;<br><br>    public void ToggleTrue()<br>    {<br>        if(_toggle.isOn == true)<br>        {<br>            Debug.Log(&quot;Toggle is On&quot;);<br>        }<br>        else<br>        {<br>            Debug.Log(&quot;Toggle is Off&quot;);<br>        }<br>    }<br>}</pre><p>In inspector attach them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*TNuAQDtyRpm66eLCnfCbyA.png" /></figure><p>This is how it works works.</p><h3>Toggle Group</h3><p>Good example of Toggle Group is UI Game difficulty menu, there you have easy, medium, hard. If you tick On one of them others set to false. Let’s see how to setup this. Create 3 Toggles and put them under one empty Parent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNvDOB-x6Vv3Lq1BXwUIrw.png" /></figure><p>Then add a ToggleGroup component to this parent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*stWqFiul7RCyknjmCJw3pQ.png" /></figure><p>For each Toggle set the group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*TYRgkhlY6qq0RGKbh8037g.png" /></figure><p>then test and you see it works fine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*RAerKacb1eUpWwKEUcJQfw.png" /></figure><p>This is how they know each other exist. Multiple toggles can’t be turned on at the same time. Let’s see how to manage them inside the script. We create a new script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class ButtonManager : MonoBehaviour<br>{<br>    [SerializeField] private Toggle[] _toggles;<br><br>    public void Toggle0True()<br>    {<br>        if (_toggles[0].isOn == true)<br>            Debug.Log(&quot;Game Difficulty is set Easy!&quot;);<br>    }<br><br>    public void Toggle1True()<br>    {<br>        if (_toggles[1].isOn == true)<br>            Debug.Log(&quot;Game Difficulty is set Medium!&quot;);<br>    }<br><br>    public void Toggle2True()<br>    {<br>        if (_toggles[2].isOn == true)<br>            Debug.Log(&quot;Game Difficulty is set Hard!&quot;);<br>    }<br>}</pre><p>Let’s create an empty ButtonManager and attach the script to it, set the inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*Y-EwC6wT_IeMBDqMLPtwGw.png" /></figure><p>and set for each toggle it’s function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*9XzFes6PrT_RHmsgT-DnRA.png" /></figure><p>test and see the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*rTv45c-xnyDGApGfX0RJzw.png" /></figure><p>That’s how we use toggle group.</p><h3>Challenge: Playtime Rules with Toggle</h3><p>This is a common use of toggle group. for each toggle button set active it’s own UI picture and rule text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*N_uxFcKWBuLbE4U8qq3U2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*pvigX3AXLGUHYcx46FZp3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*_JAOXkyv13hS-alfRQNjBA.png" /></figure><p>This for example. So how to setup this. First we prepare UI background canvas as usual. Then we create this hierarchy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*fSFmqqCgKWie7EazzTHwsA.png" /></figure><p>And a script to control it:</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class PlaytimeManager : MonoBehaviour<br>{<br>    [SerializeField] private Toggle[] _toggles;<br>    [SerializeField] private GameObject[] _rules;<br><br>    public void Toggle0True()<br>    {<br>        if (_toggles[0].isOn == true)<br>            foreach(GameObject rule in _rules)<br>            {<br>                rule.SetActive(false);<br>            }<br>        _rules[0].SetActive(true);<br>    }<br><br>    public void Toggle1True()<br>    {<br>        if (_toggles[1].isOn == true)<br>            foreach (GameObject rule in _rules)<br>            {<br>                rule.SetActive(false);<br>            }<br>        _rules[1].SetActive(true);<br>    }<br><br>    public void Toggle2True()<br>    {<br>        if (_toggles[2].isOn == true)<br>            foreach (GameObject rule in _rules)<br>            {<br>                rule.SetActive(false);<br>            }<br>        _rules[2].SetActive(true);<br>    }<br>}</pre><p>Or you can delete rules2–3 parents and manage with only one, script will be different</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br>using TMPro;<br><br>public class PlaytimeManager : MonoBehaviour<br>{<br>    [SerializeField] private Toggle[] _toggles;<br>    [SerializeField] private Sprite[] _pics;<br>    [SerializeField] private Image _image;<br>    [SerializeField] private Image _crossMarkImage;<br>    [SerializeField] private Sprite[] _crossMarkPics;<br>    [SerializeField] private TMP_Text _textfield;<br><br>    public void Toggle0True()<br>    {<br>        if(_toggles[0].isOn == true)<br>        {<br>            _image.sprite = _pics[0];<br>            _crossMarkImage.sprite = _crossMarkPics[1];<br>            _textfield.color = Color.red;<br>            _textfield.text = &quot;Don&#39;t feed the dinosaur!&quot;;<br>        }<br>    }<br><br>    public void Toggle1True()<br>    {<br>        if (_toggles[1].isOn == true)<br>        {<br>            _image.sprite = _pics[1];<br>            _crossMarkImage.sprite = _crossMarkPics[1];<br>            _textfield.color = Color.red;<br>            _textfield.text = &quot;Don&#39;t talk to the dinosaur!&quot;;<br>        }<br>    }<br><br>    public void Toggle2True()<br>    {<br>        if (_toggles[2].isOn == true)<br>        {<br>            _image.sprite = _pics[2];<br>            _crossMarkImage.sprite = _crossMarkPics[0];<br>            _textfield.color = Color.green;<br>            _textfield.text = &quot;You can hug the dinosaur!&quot;;<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*-4SfsYxaulOQRIhGUfRKLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*CyljuPJuvyKS_s96WwldMQ.png" /></figure><p>you also can set the start state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*iFuiQ1f7Cm6A9ohBvt5gDQ.png" /></figure><h3>Sliders in UI</h3><p>If you create a UI slider it will have these default structure and options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-6dmiw-ulo6H2hf8fTlkg.png" /></figure><p>Color and navigation settings are the same as buttons, these options are only for sliders</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*rGqVdb_d0NWlEi60gwEyAw.png" /></figure><p>fill react and handle attachments, direction, min/max value. Very usefull and main options. Also there are background, fill and handle colors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*pGG7gjMYj2sm3luEYyzsYA.png" /></figure><p>You also can hide this handle or make it transparent, you can make fill area and background edgs more roundness or rectangular by Pixels per unit multiplier option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Svrp5uc9rJOXQgMCsqrWqw.png" /></figure><p>you also can tick off interactable and hide the handle then player can’t interact and drag the handle, it is more suitable for health bars for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9sljNue5C1P-GDjrZBvnA.png" /></figure><p>There are other options to explore check them on your own.</p><h3>Sliders to Text Field</h3><p>Sometimes we need to show slider’s value by text above or near the slider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*cYBfwvJOzJWPhUdeamEWvw.png" /></figure><p>We can do it by script. Let’s creae a UI text and script also an empty manager object to store the script.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br>using TMPro;<br><br>public class IntSlider : MonoBehaviour<br>{<br>    [SerializeField] private Slider _slider;<br>    [SerializeField] private TMP_Text _text;<br><br>    private void Update()<br>    {<br>        _text.text = _slider.value.ToString();<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*QuGYZGP9WRhlecXrqw8AgQ.png" /></figure><h3>Challenge: Health Bar</h3><p>We want to setup a helthbar under slider there must be health value textwhich can move with the handle, handle is unvisible, also we want to change the value by 20 step, max value is 100.</p><p>Let’s first create our UI objects, make slider background and fill rectangle without round edges, adjust colors, create health label text near the slider and health value text under handle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxBvDL7jhRiRyWZlAGdc8Q.png" /></figure><p>In this picture the value is 100 which is maximum, fill color is green, but we see red color at the end, also we can see little green part when value is 0. These are default offsets in fill area, we have to set them to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*BsvCvWVUKg21uMkIqHJxDQ.png" /></figure><p>Now our UI objects are ready, time to create a new script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br>using TMPro;<br><br>public class HealthBar : MonoBehaviour<br>{<br>    [SerializeField] private Slider _slider;<br>    [SerializeField] private TMP_Text _healthValuetxt;<br>    [SerializeField] private int _health;<br><br>    void Start()<br>    {<br>        _health = 100;<br>        _slider.value = _health;<br>        _healthValuetxt.text = _health.ToString();<br>    }<br>    <br>    void Update()<br>    {<br>        if(Input.GetKeyDown(KeyCode.A))<br>        {<br>            if (_health &lt;= 0) return;<br>            _health -= 20;<br>            _slider.value = _health;<br>            _healthValuetxt.text = _health.ToString();<br>        }<br>        if (Input.GetKeyDown(KeyCode.D))<br>        {<br>            if (_health &gt;= 100) return;<br>            _health += 20;<br>            _slider.value = _health;<br>            _healthValuetxt.text = _health.ToString();<br>        }<br>    }<br>}</pre><p>attach required [SerializeField]s and test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*FF3EvZ8Ow1CcOTgxQoXFgg.png" /></figure><h3>Challenge: Loading Bar</h3><p>Let’s see how to create loading slider while the next scene is loading.</p><p>For this I actually copied UI elements from health bar changed text and colors. We also need a new scene, try to make it heavy, put there some heavy prefabs, so the loading will be enough slow to see how it is filling, also we need a new script LevelManager.</p><p><a href="https://docs.unity3d.com/2017.3/Documentation/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html">Unity - Scripting API: SceneManagement.SceneManager.LoadSceneAsync</a></p><p>here we have a good example of using <a href="https://docs.unity3d.com/2017.3/Documentation/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html">SceneManager.LoadSceneAsync</a> command. This loads the Scene asynchronously in the background.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br>using TMPro;<br>using UnityEngine.SceneManagement;<br><br>public class LevelManager : MonoBehaviour<br>{<br>    [SerializeField] private Slider _slider;<br>    [SerializeField] private TMP_Text _loadingValuetxt;<br><br>    private void Start()<br>    {<br>        _slider.value = 0;<br>        _loadingValuetxt.text = _slider.value.ToString();<br>    }<br><br>    void Update()<br>    {<br>        if(Input.GetKeyDown(KeyCode.Space))<br>            StartCoroutine(&quot;LoadLevel&quot;);<br>    }<br><br>    IEnumerator LoadLevel()<br>    {<br>        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(&quot;NextScene&quot;);<br>        while(!asyncOperation.isDone)<br>        {<br>            _slider.value = asyncOperation.progress;<br>            _loadingValuetxt.text = asyncOperation.progress.ToString();<br>            yield return null;<br>        }<br>    }<br>}</pre><p>To test it press space key and see the loading progress. Don’t forget to add NextScene in BuildSettings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*hnYfV4n4PaPL_3qpqAJNgA.png" /></figure><p>I thing better to continue the topic in the next part…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd85f0161a7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GME 303: Game Logic & Interactions II. Part-2]]></title>
            <link>https://medium.com/@yanvar103/gme-303-game-logic-interactions-ii-part-2-b5a97c678297?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5a97c678297</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 06:34:51 GMT</pubDate>
            <atom:updated>2026-10-28T06:34:51.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>Puzzle Mechanics — Power Core</h3><p>Here Player have to complete the puzzle with Powe core to powerup the elevator. Logic is: We got 3 powerChargers and 1 powerCore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*7CrNOhAtzL1WU2kL5chnew.png" /></figure><p>Before this Player’s role was only interacting with objects, now in this task Player have to also carry objects(power core) with him, power core isn’t going to be added to the inventory. So Player is going to physically hold this item and walk around and be able to drop/pickup it. These chargers have different values of charge, when we powered up the core correctly we place it to the reciever near the elevator, then the elevator will work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*K6TB7RXVMnSRYLug99RGGA.png" /></figure><p>What is the relationship between these objects: Player is just an interaction porsion, power core itself is just detecting if it is picked up or dropped and it also holds it’s power level. Chargers are going to add or subtract some amount of power level to the power core. When power core is dropped to elevator power reciever it checks if the power core has the right amount of power aviable, then the power reciever is going to add the target to elevator and the elevator will be able to work.</p><p>Let’s start with power core behaviour. We know it must be physically based, so we need rigidbody and a reference to it in PowerCore class, also bool check _isPickedup. Here we got psydo code for it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*gXaiNDd8ZAF3YC-X89Riug.png" /></figure><p>first we make it IInteractable inherited, because it is interactable object.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PowerCore : MonoBehaviour, IInteractable<br>{<br>    private Rigidbody _rb;<br>    [SerializeField] private bool _isPickedUp;<br>    [SerializeField] private Transform _playerPickupTransform;<br><br>    private void Start()<br>    {<br>        _isPickedUp = false;<br>        _rb = GetComponent&lt;Rigidbody&gt;();<br>    }<br><br>    public void Interact()<br>    {<br>        //Check if picked up or dropped<br>        if(!_isPickedUp)<br>        {<br>            _isPickedUp = true;<br>            //Turn off physics gravity when picked up<br>            _rb.isKinematic = true;<br>            <br>            //Update the position of the power core to a pickup transform on the player<br>            transform.position = _playerPickupTransform.position;<br>            transform.rotation = _playerPickupTransform.rotation;<br>            <br>            //Set the Player as the parent when picked up<br>            transform.SetParent(_playerPickupTransform);<br>        }<br>        else<br>        {<br>            _isPickedUp = false;<br>            //Turn off physics gravity when picked up<br>            _rb.isKinematic = false;<br>            <br>            //Reset the parent back to the world on drop<br>            transform.SetParent(null);<br>        }<br>    }<br><br>    public void Activate(bool _isActive) { }<br>}</pre><p>Now we add to this object our interactable elements as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYcmRxP9j_WJ5ypJacDKGg.png" /></figure><p>We also added rigidbody and PowerCore script and it asks for PlayerPickupTransform. We add an empty object under PlayerArmature in front of his belly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*VfTXPwBKy7TSnG9YW5j9TA.png" /></figure><p>If we test it we see the MainCamera starts to show from belly of the player, it is because the camera is trying to avoid collison with objects which are on default layer iscluding power core.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*4ZZ4IVIaJ5fHePNs1ykf3w.png" /></figure><p>To fix it I set the power core object’s layer to PhysicsObjects and say no for child objects, as UITransform must be in UI layer. But one thing is that our Player can push, kick this object while walking. Now power core is ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*nwzw1jcZTDlw4I1JgUpMaw.png" /></figure><h3>Creating the Power Base</h3><p>Now it’s time to drop it to the base. We are going to set them different, someones recieves the power someones is going to add a power. We need a separate class PowerBase which is common to all powerchargers and recievers. It will be responsible for interaction part, another class will be responsible for power calculations. So let’s setup the PowerBase. Here we’ll use OnCollisionEnter/Exit instead of trigger</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PowerBase : MonoBehaviour<br>{<br>    [SerializeField] private Transform _snapPoint;<br>    private bool _isBusy = false;<br><br>    private void OnCollisionEnter(Collision collision)<br>    {<br>        if (_isBusy) return; // already holding one<br>        if (collision.gameObject.CompareTag(&quot;PowerCore&quot;))<br>        {<br>            _isBusy = true;<br>            Debug.Log(&quot;Power Core Detected!&quot;);<br>            //Match the transform of the power core to the power base<br>            collision.transform.position = _snapPoint.position;<br>            collision.transform.rotation = _snapPoint.rotation;<br>        }<br>    }<br><br>    private void OnCollisionExit(Collision collision)<br>    {<br>        if (collision.gameObject.CompareTag(&quot;PowerCore&quot;))<br>        {<br>            _isBusy = false;<br>            Debug.Log(&quot;Power Core Removed!&quot;);<br>        }<br>    }<br>}</pre><p>Snap point an empty transform under the PowerCharger, it is kind a socket where core must snap, in our case it is a top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wvJz209j7xI-2jiN335oKA.png" /></figure><h3>Scripting the Power Charger</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*CXBdSECACNrxPL3ilSizyA.png" /></figure><p>For calculating power level between powerChargers we use separate scriptableObject PowerLevel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*2hM41xabFRYSk1DTaKYZUA.png" /></figure><p>What is ScriptableObject?</p><blockquote>A <strong>ScriptableObject</strong> is a Unity class for storing data as an <strong>asset in your project</strong>, not as a component on a GameObject.</blockquote><blockquote>A MonoBehaviour lives on an object in a scene. A ScriptableObject lives in your Project folder, like a material or a texture. You create it once, and any number of objects or scenes can reference it.</blockquote><blockquote>Why use one</blockquote><blockquote><strong>Shared data without duplication.</strong> If 50 enemies each carry health = 100, that value is copied 50 times. With a ScriptableObject, they all point to one asset, and changing it updates all of them.</blockquote><blockquote><strong>Designer-friendly.</strong> You tweak values in the Inspector without touching code or scenes.</blockquote><blockquote><strong>No scene dependency.</strong> The data survives scene loads because it isn’t tied to any scene.</blockquote><blockquote><strong>Memory.</strong> One shared copy instead of many.</blockquote><p>Let’s see how it works. //Inherit from PowerBase means this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*hfyrpxS810lcKel6GSCQ3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*srljS4hrW-LSjkDrO4D58w.png" /></figure><p>We see there is 1 reference above it.</p><blockquote><strong>Inheriting</strong> from a class means your new class automatically gets everything the parent class already has: its variables, its methods and its behavior. On top of that, you can add your own features.</blockquote><blockquote>In C# you write it with a colon:</blockquote><blockquote>public class PowerCore : MonoBehaviour</blockquote><blockquote>This reads as “PowerCore <strong>inherits from</strong> MonoBehaviour.” PowerCore is the <strong>child</strong> (also called the derived class or subclass), and MonoBehaviour is the <strong>parent</strong> (also called the base class).</blockquote><p>//Detect collision from PowerCore, to do this we need override void that overrites the same method from PowerBase with the same pattern</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*odxGcXEMZ7rrzuDuuM_Ulw.png" /></figure><p>In PowerBase we correct it to public virtual</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*whNqJnQl9Liv1uIKqI17ng.png" /></figure><p><strong>override</strong> means “replace the parent class’s version of this method with my own.”</p><blockquote>Override Rules</blockquote><blockquote>The method name, return type and parameters must match the parent’s exactly.</blockquote><blockquote>You can’t override a method unless the parent marked it virtual, abstract or override.</blockquote><blockquote>override works with any return type, not just void, for example public override int GetDamage().</blockquote><p>So here how we are using here an override</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R4cwbEhVSRv3bJz33Y9pw.png" /></figure><p>To apply the power level first we need to define them in powerCore and PowerLevel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*56mQ8NXCJXeSlefKxlTDxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*golJ-K4yIDoxSE9dKhOikQ.png" /></figure><p>then we can apply it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOuuuosuzqaG3YoeuUgcWg.png" /></figure><p>Now let’s go back to editor and set them, I’ll remove th PowerBase script from charger objects and add, inherited from it, PowerCharger script then override changes in prefab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*_3NNDROyA7wvTnn32RZwhA.png" /></figure><p>You can see it requires Power Level, I’ll create a new Scriptable Objects folder in Assets, then that scriptable object must appear on top of this menu</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*OAvkeFtEj0yPE_ZycSMN3Q.png" /></figure><p>for this we need to add this line here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*_P372QRceRkdrD4f2AXWog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*r-zufJf3XLw-eSF7LLKFCQ.png" /></figure><p>We also can use / to make submenus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*XNgjks81lNP-LzHygoGTuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*GeZx79VJ3PQLmxovHC35YQ.png" /></figure><p>Now I’ll add several PowerLevels with different amounts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*9msDD1yuG-dSr71txYFDNA.png" /></figure><p>Large -15, medium -10, small -5, smallReduction — (-5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*42R0j7qeugZVO-v91f0iag.png" /></figure><p>Now for every charge in scene designer set’s it’s own chargeLevel in inspector, for example, chargerA will be with large charge level of 15, this means if player places core onto this chargerA power core’s power level increases to 15. With this designer can create a math puzzle with powerLevels</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XheFbjzozUuWHP9d606_SA.png" /></figure><p>Let’s set the power reciever</p><h3>Transferring Power to the Power Receiver</h3><p>We need this kind of functionality</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*pc2PmSxPgi4lDV2OvjS49Q.png" /></figure><p>Here is the solution, nothing new for this time</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PowerReciever : PowerBase //Inherit from the PowerBase<br>{<br>    //Allow designer to input the required power level<br>    [SerializeField] private int _requiredPowerLevel;<br><br>    //have a target be powered up by the reciever(elevator)<br>    [SerializeField] private GameObject[] _targets;<br>    [SerializeField] private bool _isActivated;<br><br>    public override void OnCollisionEnter(Collision collision)<br>    {<br>        base.OnCollisionEnter(collision);<br>        //Check if the power core is on the reciever<br>        if (collision.gameObject.CompareTag(&quot;PowerCore&quot;))<br>        {<br>            //Check if the power level is sufficient<br>            int powerCoreValue =  collision.gameObject.GetComponent&lt;PowerCore&gt;().powerLevel;<br>            if (powerCoreValue == _requiredPowerLevel)<br>            {<br>                Debug.Log(&quot;Sufficient power!&quot;);<br>                _isActivated = true;<br>                foreach (GameObject _target in _targets)<br>                {<br>                    if (_target.TryGetComponent&lt;IInteractable&gt;(out IInteractable interactable))<br>                        interactable.Activate(_isActivated);<br>                }<br>            }<br>            else if (powerCoreValue &gt; _requiredPowerLevel)<br>                Debug.Log(&quot;Too much power!&quot;);<br>            else<br>                Debug.Log(&quot;Insufficient power!&quot;);<br>        }<br>    }<br>}</pre><p>One thing we need to add here is deactivate targets when powercore is removed, for this we need first change OnCollisionExit method to virtual in PowerBase then extend it in PowerReciever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*JoP8mrqxS5obmLSxGf3_8Q.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PowerReciever : PowerBase //Inherit from the PowerBase<br>{<br>    //Allow designer to input the required power level<br>    [SerializeField] private int _requiredPowerLevel;<br><br>    //have a target be powered up by the reciever(elevator)<br>    [SerializeField] private GameObject[] _targets;<br>    [SerializeField] private bool _isActivated;<br><br>    public override void OnCollisionEnter(Collision collision)<br>    {<br>        base.OnCollisionEnter(collision);<br>        //Check if the power core is on the reciever<br>        if (collision.gameObject.CompareTag(&quot;PowerCore&quot;))<br>        {<br>            //Check if the power level is sufficient<br>            int powerCoreValue =  collision.gameObject.GetComponent&lt;PowerCore&gt;().powerLevel;<br>            if (powerCoreValue == _requiredPowerLevel)<br>            {<br>                Debug.Log(&quot;Sufficient power!&quot;);<br>                _isActivated = true;<br>                foreach (GameObject _target in _targets)<br>                {<br>                    if (_target.TryGetComponent&lt;IInteractable&gt;(out IInteractable interactable))<br>                        interactable.Activate(_isActivated);<br>                }<br>            }<br>            else if (powerCoreValue &gt; _requiredPowerLevel)<br>                Debug.Log(&quot;Too much power!&quot;);<br>            else<br>                Debug.Log(&quot;Insufficient power!&quot;);<br>        }<br>    }<br><br>    public override void OnCollisionExit(Collision collision)<br>    {<br>        base.OnCollisionExit(collision);<br>        _isActivated = false;<br>    }<br>}</pre><p>Now let’s test it, we’ll try it with required level 15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*dlZHZ4hOCE01rn16MmyGYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBubXtRJl_ssh5m1oPu5UA.png" /></figure><p>tried all 3 statements, it works.</p><h3>Changing the Power Core Color</h3><p>In textures we have this color guide, we set the color according to this reference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*aB3vKAE-NKBJezMnXfBmsA.png" /></figure><p>First we need references to reciever and powerCoreMaterial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oM65VIi92SLgrUVFr17Yw.png" /></figure><p>then we add this public method in PoweCore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*BXd980KwkVOdXU4dxUfO_g.png" /></figure><p>Then call it from PowerCharger class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eorHTDu6c062j1pwBCWjdw.png" /></figure><p>we attach the power reciever object to it and test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*G9Wfsw1SDE6yVBybMmniCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*-iFrL1NOqBFlIxkNWxlPWw.png" /></figure><p>Now once we have done with setting up the Puzzle let’s set the target -elevator.</p><h3>Elevators. Creating the Base Elevator Functionality</h3><p>Let’s create a new Elevator class, here what we are going to do in it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*44k5kY05D1QTlek_9c8w_A.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Elevator : MonoBehaviour, IInteractable<br>{<br>    //Multi-levels<br>    public Transform[] elevatorLevels;<br>    //Drive the speed of the elevator<br>    [SerializeField] private float _elevatorSpeed = 10f;<br>    public bool _isPoweredUp;<br>    [SerializeField] private bool _isCalled;<br><br>    //Check which level we&#39;re currently at<br>    //Determine which level to go to next<br>    [SerializeField] private int _nextLevelIndex;<br><br>    //Move the elevator to the next position<br>    private void Update()<br>    {<br>        if(_isCalled)<br>        {<br>            float distance = Vector3.Distance(transform.position, elevatorLevels[_nextLevelIndex].position);<br>            transform.position = Vector3.MoveTowards(transform.position, elevatorLevels[_nextLevelIndex].position, Time.deltaTime * _elevatorSpeed);<br>            if(distance == 0)<br>            {<br>                _isCalled = false;<br>                _nextLevelIndex ++;<br>                if (_nextLevelIndex == elevatorLevels.Length)<br>                    _nextLevelIndex = 0;<br>            }<br>        }<br>    }<br><br>    public void Interact()<br>    {<br>        //Check if the elevator activated<br>        if (_isPoweredUp)<br>            _isCalled = true;<br>    }<br><br>    public void Activate(bool _isActive)<br>    {<br>        _isPoweredUp = _isActive;<br>    }<br>}</pre><p>Here is a solution, here it without determining the direction(up/down), it’s ok for now, let’s set them in elevator prefab editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Vipds43lM6jStj0779R9NA.png" /></figure><p>Then I swapped elevator level elements to match the script indexes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ajbQC4ivTIpeqDudIYYdIQ.png" /></figure><p>By script start index is 0(Level_01), then it goes up(Level_02), then down(Level_00), then to start(Level_01) and keeps repeating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*ygtBPKeXGELN36JokIE0Vg.png" /></figure><p>When platform goes up Player looks little bit jittery, when goes down Player is kind of falling down, physically maybe it’s correct, but we want the player to be planted on the platform while it is moving. We’ll fix this with parenting Player under platform.</p><p>For this we use a new script ChangeParentTrigger</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class ChangeParentTrigger : MonoBehaviour<br>{<br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if(other.gameObject.CompareTag(&quot;Player&quot;))<br>        {<br>            other.transform.SetParent(transform);<br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        if (other.gameObject.CompareTag(&quot;Player&quot;))<br>        {<br>            other.transform.SetParent(null);<br>        }<br>    }<br>}</pre><p>Now under the Platform we’ll create a new empty object with trigger collider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYWAuduBjfZXtWNksL_fTw.png" /></figure><p>Now let’s test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*DqLggKPorgAnaYPCaPFj2w.png" /></figure><p>When player gets onto the platform it is under ChangeParentTrigger object and in the world when Player exits as intended.</p><p>One more thing is a Camera issue, when platform moves fast Camera is lagging behind because of damping. We can set the damping to 0. Also Camera moves in/out colliding with floor obstacles while moving up/down. For this we can decrease camera distance inside it’s body settings. Let’s see how to fix this through code.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using Cinemachine;<br><br>public class ChangeParentTrigger : MonoBehaviour<br>{<br>    [SerializeField] private CinemachineVirtualCamera _vCam;<br>    private Cinemachine3rdPersonFollow _3PersonFollow;<br>    private Vector3 _vCamDampingOrig;<br>    private float _vCamDistOrig;<br>    [SerializeField] private float _vCamDistElevator;//set in inspector<br><br>    private void Start()<br>    {<br>        _3PersonFollow = _vCam.GetCinemachineComponent&lt;Cinemachine3rdPersonFollow&gt;();<br>        _vCamDampingOrig = _3PersonFollow.Damping;<br>        _vCamDistOrig = _3PersonFollow.CameraDistance;<br>    }<br><br><br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if(other.gameObject.CompareTag(&quot;Player&quot;))<br>        {<br>            other.transform.SetParent(transform);<br>            //Change the camera distance<br>            _3PersonFollow.CameraDistance = _vCamDistElevator;<br>            //Set the damping to 0<br>            _3PersonFollow.Damping = new Vector3(_vCamDampingOrig.x, 0, _vCamDampingOrig.z);<br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        if (other.gameObject.CompareTag(&quot;Player&quot;))<br>        {<br>            other.transform.SetParent(null);<br>            //Revert all camera changes to original<br>            _3PersonFollow.CameraDistance = _vCamDistOrig;<br>            _3PersonFollow.Damping = _vCamDampingOrig;<br>        }<br>    }<br>}</pre><p>I still have a jittering issue, UI element is also jittering while the elevator is moving.</p><p>Since the elevator moves with transform.position in Update, the elevator itself is fine. The UI object jittering is a useful clue: it means the camera is out of sync with the platform, not just the player. When the player jitters, the camera following it with Y damping 0 makes the whole world appear to shake, including UI.</p><p>Solution: we have to make the elevator move first and sync physics. Elevator Update and the player controller’s Update run in random order. If the player’s CharacterController.Move() runs first, it works from a stale capsule position. Every frame it alternates between “moved by parent” and “snapped back”, which is jitter. Make the elevator always run first and sync the transforms after moving:</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>[DefaultExecutionOrder(-100)] // run before the player controller<br><br>public class Elevator : MonoBehaviour, IInteractable<br>{<br>    //Multi-levels<br>    public Transform[] elevatorLevels;<br>    //Drive the speed of the elevator<br>    [SerializeField] private float _elevatorSpeed = 10f;<br>    public bool _isPoweredUp;<br>    [SerializeField] private string _howToActivate;<br>    [SerializeField] private bool _isCalled;<br><br>    //Check which level we&#39;re currently at<br>    //Determine which level to go to next<br>    [SerializeField] private int _nextLevelIndex;<br><br>    //Move the elevator to the next position<br>    private void Update()<br>    {<br>        if (!_isCalled) return;<br><br>        Vector3 target = elevatorLevels[_nextLevelIndex].position;<br>        transform.position = Vector3.MoveTowards(transform.position, elevatorLevels[_nextLevelIndex].position, Time.deltaTime * _elevatorSpeed);<br><br>        // Sync the CharacterController&#39;s capsule with its new (parented) position<br>        Physics.SyncTransforms();<br><br>        if (transform.position == target) // checked AFTER moving<br>        {<br>            _isCalled = false;<br>            _nextLevelIndex = (_nextLevelIndex + 1) % elevatorLevels.Length;<br>        }<br>    }<br><br>    public void Interact()<br>    {<br>        //Check if the elevator activated<br>        if (_isPoweredUp)<br>            _isCalled = true;<br>        else<br>            Debug.Log(_howToActivate);<br>    }<br><br>    public void Activate(bool _isActive)<br>    {<br>        _isPoweredUp = _isActive;<br>    }<br>}</pre><p>I also moved the arrival check to after the move. previous version measured the distance before moving, so the elevator stopped one frame late. So after this fix there is no jittering.</p><p>Instead of calling Physics.SyncTransforms() in code, you can enable <strong>Project Settings → Physics → Auto Sync Transforms</strong>. Either one works.</p><blockquote>[DefaultExecutionOrder(-100)] is an attribute that tells Unity <strong>when this script’s </strong><strong>Update (and </strong><strong>Awake, </strong><strong>Start, </strong><strong>LateUpdate, etc.) runs compared to other scripts</strong>.</blockquote><h3>Extending the Player Input System</h3><p>With 3rdPersonController starter asset we have already prepared input system actions. In our created scripts we are using legacy input. Now we can add interaction input as a new input action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*KVKaRR8FZsT9a-c7lzQs5g.png" /></figure><p>These actions are sutiable also for GamePad</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*x3E8X2uZfyLAsE6Wom_ZHw.png" /></figure><p>Here we can add new action for interactions(action type button)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*RFra1oK98CLVzEUj4rYxVw.png" /></figure><p>Save asset and exit.</p><p>Then open StarterAssetsInputs. All you need to do is add there our new interact action methods by analogy of existing one(sprint for example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*3nG56ml1riOtXaraB4Dv8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*QN0PInzIR1JwEDZOtVmq5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*8xFfvMUetxVLFyqseAAZUA.png" /></figure><p>The way how to use extended interact system in our StarterAssetsInputs is to use separate class InteractInputExtension. You can do it by modifying existing StarterAssetsInputs, but if we have a system which is already have been built, better to create a new script wich is going to borrow from that. We’ll going to attach it to Player object.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using StarterAssets;<br><br>public class InteractInputExtension : MonoBehaviour<br>{<br>    private StarterAssetsInputs _starterAssetsInputs;<br><br>    private void Awake()<br>    {<br>        _starterAssetsInputs = GetComponent&lt;StarterAssetsInputs&gt;();<br>    }<br><br>    private void LateUpdate()<br>    {<br>        _starterAssetsInputs.interact = false; //sets it to false right after interacting<br>    }<br>}</pre><p>All I’m doing here is setting it to false at the end of frame in lateUpdate right after interacting. Then in our Interactable class we replace the old input with this new one, actually it simply listens for that interact code to fire off. So add these lines</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tx_WyddAOK1FIy2DTodFng.png" /></figure><p>then replace this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*DIasBzxN8gj_qc2CGh8tow.png" /></figure><p>So after we press the button StarterAssetsInputs sets interact to true, then after interaction happened on lateUpdate InteractInputExtension sets it to false. Don’t forget to attach it to Player object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*ZykbEF8k6IeDAN7UQI8aJA.png" /></figure><p>I tested it works, one note, elevator still working after detaching the powerCore. But input action by itself is working.</p><h3>Creating a UI Action Map</h3><p>One of the reasons why we implemented new input system is necessity of using pop up UI menus with it’s own navigation input(UI action map). When we interact with the elevator, UI menu must appear on screen and W, S keys must switch to menu navigation from Player walk. On this menu Player can choose the level to move.</p><p>First step is creating a navigation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*fuxYIMGoh31FliTE1qkV6Q.png" /></figure><p>I recommend to set Control scheme for every binding making them exclusive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*2Rdiitn75QJVh8gY2XDg8Q.png" /></figure><p>Next is to add submit and cancel actions. In Packages/Input System/Input System/Plugins/PlayerInput/DefaultInputActions you can find lot’s of common actions for UI action map. You can borrow them as example. Explore them on your own. So I’ll make our own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*m314dvr2-GP2KGo6m6YWqQ.png" /></figure><h3>Setting Up the Player and Event System</h3><p>In PlayerArmature it has Player Input component, which is from Unity new Input System package. You can see it uses starter assets action maps and the default map is set to Player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*7WFAKpyigneCk_4YuJNrWw.png" /></figure><p>Once we added UI in list you can see also UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*iAu-CoVlcZo4DV3bZ_mccw.png" /></figure><p>In UI Input Module we have to set Event system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*L3L-bcwLTPpnvIR2BmBojA.png" /></figure><p>If you select the EventSystem in scene hierarchy you find InputSystemUIInputModule component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*aFvmmXWDTwRDj_RCBc68KQ.png" /></figure><p>All I need here is to set StarterAssets as Action Asset. Other settings are correct</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*DSgxvvmmXP75JGE9YOdTwA.png" /></figure><p>After attaching one more thing to set is move, set it to UI/navigation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*MVpHF7WeYbWu6M_0CE0Qlg.png" /></figure><h3>Swapping the Player and UI Action Maps</h3><p>We have already prepared elevator UI canvas inside Prefabs. Drag it to the scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oEnV2lC-B-UTgFSTax_ig.png" /></figure><p>Now we are going to implement this UI in Elevator class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RUbADggG8t4tNFWC786wng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*RxtoPomtacbzHTt6A0RW6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*H0gOE9PY-eFfB2fzB2jTNQ.png" /></figure><p>So here is a solution</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>[DefaultExecutionOrder(-100)] // run before the player controller<br><br>public class Elevator : MonoBehaviour, IInteractable<br>{<br>    //Multi-levels<br>    public Transform[] elevatorLevels;<br>    //Drive the speed of the elevator<br>    [SerializeField] private float _elevatorSpeed = 10f;<br>    public bool _isPoweredUp;<br>    [SerializeField] private string _howToActivate;<br>    [SerializeField] private bool _isCalled;<br><br>    //Check which level we&#39;re currently at<br>    //Determine which level to go to next<br>    [SerializeField] private int _nextLevelIndex;<br><br>    //Reference to the Player Input<br>    private PlayerInput _playerInput;<br>    //Reference to the Elevator UI<br>    [SerializeField] private GameObject _elevatorUI;<br><br>    private void Awake()<br>    {<br>        _playerInput = GameObject.FindWithTag(&quot;Player&quot;).GetComponent&lt;PlayerInput&gt;();<br>        _elevatorUI.SetActive(false);<br>    }<br><br>    //Move the elevator to the next position<br>    private void Update()<br>    {<br>        if (!_isCalled) return;<br>        if (!_isPoweredUp) return;<br><br>        Vector3 target = elevatorLevels[_nextLevelIndex].position;<br>        transform.position = Vector3.MoveTowards(transform.position, elevatorLevels[_nextLevelIndex].position, Time.deltaTime * _elevatorSpeed);<br><br>        // Sync the CharacterController&#39;s capsule with its new (parented) position<br>        Physics.SyncTransforms();<br><br>        if (transform.position == target) // checked AFTER moving<br>        {<br>            _isCalled = false;<br>            _nextLevelIndex = (_nextLevelIndex + 1) % elevatorLevels.Length;<br>        }<br>    }<br><br>    public void Interact()<br>    {<br>        //Check if the elevator activated<br>        if (_isPoweredUp)<br>        {<br>            //Show the Elevator UI<br>            _elevatorUI.SetActive(true);<br>            //Activate UI action map<br>            _playerInput.SwitchCurrentActionMap(&quot;UI&quot;);<br>        }<br>        else<br>            Debug.Log(_howToActivate);<br>    }<br><br>    public void Activate(bool _isActive)<br>    {<br>        _isPoweredUp = _isActive;<br>    }<br><br>    //New method to check floor int value from OnClick event<br>    public void ChooseFloor(int floorValue)<br>    {<br>        //Choose the floor<br>        _nextLevelIndex = floorValue;<br>        //Hide the elevator UI<br>        _elevatorUI.SetActive(false);<br>        //Switch the action map back to Player<br>        _playerInput.SwitchCurrentActionMap(&quot;Player&quot;);<br>        _isCalled = true;<br>    }<br>}</pre><p>Now here under button UI element OnClick we’ll call our new method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*nBuNfvL2uyfVGc6vzEzelw.png" /></figure><p>For each element we set corresponding index</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*ESMgGBJtNdhGVCn3fYyGFQ.png" /></figure><p>Check if each indexations matches</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*mF3uuOAW5Jcw2PuVLSGv_g.png" /></figure><p>Also set the first selected here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*JZi-oWpyGNvV4QHaK56N_w.png" /></figure><p>You can also set button colors here, select all three, let’s say I want selected button to be red</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*wjc4TWFGUIVSIOYkt98M6Q.png" /></figure><p>Now it’s working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*0_hg8RfDfzn_bbg6Cm701g.png" /></figure><p>But one note issue, here I can interact on midway and change the destination, I want it not to be able to interact while elevator is moving. This addition can fix this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*glDARAkacp5HKRvz41mnPA.png" /></figure><p>I noticed that when I remove the power core elevator still working, to fix it in PowerReciever class inside OnCollisionExit add this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*aVUwLD_GtKgSGYTXV40F8A.png" /></figure><p>also check in Elevator class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SFQIMmZbtyRhUqcGTb4-Yw.png" /></figure><h3>Calling the Elevator via Terminal</h3><p>Next thing is to add an elevator call function in case if elevator is on another level.</p><p>We have an existing elevator, we override every modifications on it, then drag it’s prefab near to elevator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHg-d84Kq5yoAPHqI72cAg.png" /></figure><p>It also must not work if power core is detached from reciever. This is modified terminal class which includes elevator call function with power on via Activate method, in our case PowerReciever activates it via IInteractable. Also added power check and if unpowered instruction.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Terminal : MonoBehaviour, IInteractable<br>{<br>    //get target reference<br>    [SerializeField] private GameObject[] _targets;<br>    //create a reference to power up the terminal(with electricity)<br>    [SerializeField] private bool _isPowered;<br>    //Reference to the terminalFloorIndex;<br>    [SerializeField] private int _terminalFloorIndex;<br>    [SerializeField] private string _howToOpen;<br><br>    //On Interact<br>    public void Interact()<br>    {<br>        //get all of the targets<br>        //foreach target<br>        if (_isPowered)<br>        {<br>            foreach (GameObject _target in _targets)<br>            {<br>                if (_target.TryGetComponent&lt;IInteractable&gt;(out IInteractable interactable))<br>                {<br>                    Debug.Log(_target.name + &quot; is powered up!&quot;);<br>                    //activate those targers via a new method<br>                    interactable.Activate(_isPowered);<br>                    //Try to get the elevator component, if true call chooseFloor method<br>                    if (_target.TryGetComponent&lt;Elevator&gt;(out Elevator elevator))<br>                        elevator.ChooseFloor(_terminalFloorIndex);<br>                }<br>            }<br>        }<br>        else<br>            Debug.Log(_howToOpen);<br>    }<br><br>    public void Activate(bool _isActive)<br>    {<br>        //if powered off, then activate the terminal<br>        _isPowered = _isActive;<br>    }<br>}</pre><p>We need to add this Terminal to reviever target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*9pbyO9kVNWxy1PIKUueIoQ.png" /></figure><p>Also set the TerminalFloorIndex to 1 as we planted it to 1st floor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*jFrp0pqr0uG2VWMFnmyaYw.png" /></figure><h3>Project Review</h3><p>We have Debug log messages for how to open/activate/powerUp instructions, Player cannot see it when project is built, so we need to implement them to UI text. For this we create a new UIMessageDisplay.cs which is a small singleton that any class can call with one line, so you don’t need to drag a UI reference into every script.</p><pre>using System.Collections;<br>using UnityEngine;<br>using TMPro;<br><br>// Put this on any GameObject in the scene (e.g. your Canvas) and drag<br>// your existing UI text into the _messageText slot in the Inspector.<br>// Any script can then call: UIMessageDisplay.Show(&quot;your message&quot;);<br>public class UIMessageDisplay : MonoBehaviour<br>{<br>    public static UIMessageDisplay Instance { get; private set; }<br><br>    [SerializeField] private TMP_Text _messageText;<br>    // How long a message stays on screen (seconds)<br>    [SerializeField] private float _defaultDuration = 3f;<br><br>    private Coroutine _hideRoutine;<br><br>    private void Awake()<br>    {<br>        if (Instance != null &amp;&amp; Instance != this)<br>        {<br>            Destroy(gameObject);<br>            return;<br>        }<br>        Instance = this;<br><br>        if (_messageText != null)<br>            _messageText.gameObject.SetActive(false);<br>    }<br><br>    private void OnDestroy()<br>    {<br>        if (Instance == this)<br>            Instance = null;<br>    }<br><br>    // Static shortcut so other classes don&#39;t need a reference<br>    public static void Show(string message, float duration = -1f)<br>    {<br>        if (Instance == null)<br>        {<br>            // Fallback so you still see it in the editor if the UI is missing<br>            Debug.LogWarning(&quot;UIMessageDisplay not found in scene. Message: &quot; + message);<br>            return;<br>        }<br>        Instance.ShowMessage(message, duration);<br>    }<br><br>    public void ShowMessage(string message, float duration = -1f)<br>    {<br>        if (_messageText == null || string.IsNullOrEmpty(message))<br>            return;<br><br>        _messageText.text = message;<br>        _messageText.gameObject.SetActive(true);<br><br>        // Restart the timer if a new message comes in while one is showing<br>        if (_hideRoutine != null)<br>            StopCoroutine(_hideRoutine);<br><br>        float time = duration &gt; 0f ? duration : _defaultDuration;<br>        _hideRoutine = StartCoroutine(HideAfter(time));<br>    }<br><br>    private IEnumerator HideAfter(float seconds)<br>    {<br>        yield return new WaitForSeconds(seconds);<br>        _messageText.gameObject.SetActive(false);<br>        _hideRoutine = null;<br>    }<br>}</pre><p>On other classes where we used</p><pre>// before<br>Debug.Log(_howToOpen);<br>// after<br>UIMessageDisplay.Show(_howToOpen);<br>// or with a custom duration<br>UIMessageDisplay.Show(_howToOpen, 5f);</pre><h3>Adding UI inventory</h3><p>I’ll add a change notification to InventoryManager and a small InventoryUI script that rewrites the text whenever the list changes.</p><p><strong>How it works:</strong> OnInventoryChanged is an event, a signal the manager sends out. InventoryUI listens for it, and each time it fires, RefreshUI rebuilds the text from the list. This way the UI only updates when something actually changes, instead of checking every frame in Update.</p><pre>using System.Text;<br>using UnityEngine;<br>using TMPro;<br><br>// Put this on any GameObject in the scene (e.g. your Canvas) and drag<br>// the UI text that should show the inventory into the _inventoryText slot.<br>public class InventoryUI : MonoBehaviour<br>{<br>    [SerializeField] private TMP_Text _inventoryText;<br>    // First line of the list<br>    [SerializeField] private string _title = &quot;Inventory:&quot;;<br>    // Shown when the list is empty (leave blank to show only the title)<br>    [SerializeField] private string _emptyText = &quot;(empty)&quot;;<br><br>    private void Start()<br>    {<br>        // Subscribed in Start (not Awake/OnEnable) so InventoryManager.Instance is already set<br>        if (InventoryManager.Instance != null)<br>            InventoryManager.Instance.OnInventoryChanged += RefreshUI;<br>        else<br>            Debug.LogWarning(&quot;InventoryUI: no InventoryManager found in scene.&quot;);<br><br>        RefreshUI();<br>    }<br><br>    private void OnDestroy()<br>    {<br>        // Always unsubscribe, so the manager doesn&#39;t call a destroyed object<br>        if (InventoryManager.Instance != null)<br>            InventoryManager.Instance.OnInventoryChanged -= RefreshUI;<br>    }<br><br>    private void RefreshUI()<br>    {<br>        if (_inventoryText == null || InventoryManager.Instance == null)<br>            return;<br><br>        StringBuilder sb = new StringBuilder();<br>        sb.AppendLine(_title);<br><br>        var items = InventoryManager.Instance._inventoryItems;<br>        if (items.Count == 0)<br>        {<br>            sb.AppendLine(_emptyText);<br>        }<br>        else<br>        {<br>            foreach (var item in items)<br>                sb.AppendLine(&quot;- &quot; + ToReadableName(item.ToString()));<br>        }<br><br>        _inventoryText.text = sb.ToString();<br>    }<br><br>    // Turns &quot;KeycardA&quot; into &quot;Keycard A&quot; for nicer display<br>    private string ToReadableName(string name)<br>    {<br>        StringBuilder sb = new StringBuilder();<br>        for (int i = 0; i &lt; name.Length; i++)<br>        {<br>            if (i &gt; 0 &amp;&amp; char.IsUpper(name[i]))<br>                sb.Append(&#39; &#39;);<br>            sb.Append(name[i]);<br>        }<br>        return sb.ToString();<br>    }<br>}</pre><p>Also added Action event with Invoke() lines inside AddItems and RemoveItems in InventoryManager</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XI9zbz265btqbmSKGSpVew.png" /></figure><p>In scene added it inside MainCanvas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*NNY_zrnrLntSARZIsD5CiQ.png" /></figure><p>When you build game on WebGL and if game is gong to be runned on browser better set this resolution to make Canvas elements suitable to the screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*5x357O4qFgCDfO05xt_UZg.png" /></figure><p>So in this course we explored most used and main aspects of interactions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5a97c678297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GME 303: Game Logic & Interactions II. Part-1]]></title>
            <link>https://medium.com/@yanvar103/gme-303-game-logic-interactions-ii-part-1-a0224d078b7a?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0224d078b7a</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 12:24:29 GMT</pubDate>
            <atom:updated>2026-10-19T12:24:29.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple Collectable Items</h3><p>I’m doing this course using Unity 2022.3.55f1. In games we always use collectible items like health, ammo, etc. with which Player will interact. Let’s see how to set up health pickUp interaction. We’ll create a new script for this</p><pre>//OnTriggerEnter, collect the item<br>//Modify a player stat<br>//Destroy this gameObject</pre><p>Let’s solve it</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Interactable : MonoBehaviour<br>{<br>    //OnTriggerEnter, collect the item<br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if(other.CompareTag(&quot;Player&quot;))<br>        {<br>            //Modify a player stat<br>            Debug.Log(&quot;add Health&quot;);<br><br>            //Destroy this gameObject<br>            Destroy(gameObject);<br>        }<br>    }<br>}</pre><p>I used Debug, because now we have no any Player script yet. In inspector we add to this component another collider(sphere).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*uHp0bxOv26BwHya0M82uXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*xHDc8lR7Do0_NgrG4xbiBw.png" /></figure><p>Sphere collider is for trigger, box collider is for physics, also we add our new Interactable script. Sphere will be bigger to collect it before touching the physics collider.</p><h4>Showing and Hiding UI for Interactable Items.</h4><p>In some games when player enters the item collider some kind of text or image UI element appears on the screen and disappears when Player exits this collider. In this case we use OnTriggerStay and OnTriggerExit. Sort of this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*xoHuxk2wz-MAJr3Dt6ONYg.png" /></figure><p>There is also a prepared prefab which has it’s own canvas(world space canvas which is going to appear over the top of other items), UIContainer, Image and text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyRNMwu6EtVcPByd6kfZdQ.png" /></figure><p>Here we use enable/disable UIContainer to show/hide UI. You can see the text showing E, which means it’s waiting the Player to press E key to collect the item. Let’s use it now. We already have pickUp item prefab, we add this UITransform under this Item as a child and place little bit higher above the item and make sphere collider more bigger, we also disable the UIContainer as default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xn-MOvf08H2a4_N7j4Ty3w.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Interactable : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _UIContainer;<br><br>    private void Awake()<br>    {<br>        if (_UIContainer != null) _UIContainer.SetActive(false);<br>    }<br><br>    private void OnTriggerStay(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Player&quot;))<br>        {<br>            //Show UI<br>            if (_UIContainer != null) _UIContainer.SetActive(true);<br>            if(Input.GetKeyDown(KeyCode.E)) Debug.Log(&quot;Interacted&quot;);<br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        //Hide UI<br>        if (_UIContainer != null) _UIContainer.SetActive(false);<br>    }<br>}</pre><p>Now it works, when player gets close to the item, UI will showUp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*JDaOsH8H2WJ4O4sKOM902Q.png" /></figure><h4>Rotating the UI to Face the Camera.</h4><p>When I come to the item from another angle, from side or back it looks not as we wanted or even flipped</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*0bkzJSyUHOMWA8goXCjj_A.png" /></figure><p>We are going to modifi it little bit, make it to face the camera. Also I want it to be visible through the player’s body to make it more comfortable. Best practice is to make for this separate class and attach it to this UI element, in our case it is UIContainer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*E-BPqO8JiNC3SggLn5fe9Q.png" /></figure><p>If we type commands in update it will look little bit jittery, better to use LateUpdate. What’s the difference between them?</p><blockquote>Both are called once per frame on every active MonoBehaviour. The difference is <strong>when</strong> in the frame they run.</blockquote><blockquote><strong>Update</strong> runs first, every frame. This is where most game logic goes: reading input, moving characters, timers, and AI decisions.</blockquote><blockquote><strong>LateUpdate</strong> runs after <em>every</em> script’s Update has finished for that frame, and after animations have been evaluated. Use it for anything that needs the final positions of other objects for this frame.</blockquote><blockquote>Common uses for LateUpdate: Cameras that follow or look at something, Adjusting bones after the Animator has posed them (e.g. making a head look at a target), since the Animator would otherwise overwrite your changes, UI elements that track world objects (health bars over enemies and our case), Anything that reacts to where things ended up this frame.</blockquote><p>So in here we’ll going to use Unity’s Transform.LookAt method</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Transform.LookAt.html">Transform.LookAt</a></p><blockquote>Rotates the transform so the forward vector points at /target/’s current position.</blockquote><blockquote>Then it rotates the transform to point its up direction vector in the direction hinted at by the worldUp vector. If you leave out the worldUp parameter, the function will use the world y axis. The up vector of the rotation will only match the worldUp vector if the forward direction is perpendicular to worldUp.</blockquote><p>This is actually the script:</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class UILookAt : MonoBehaviour<br>{<br>    [SerializeField] private Transform _cameraTransform;//attach here mainCamera<br>    <br>    private void LateUpdate()<br>    {<br>        //LookAt method to change the orientation of the UI by Y axis<br>        //object looks to the target by it&#39;s face(z axis)<br>        transform.LookAt(_cameraTransform);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*_eNTvgRJaUn9HGKj56s3ZQ.png" /></figure><p>Here UIContainer objects face local axis looks backward relative to the text, as result we see flipped E letter in play mode, we can fix it inside the script or attach this script to parent object(UITransform) which z axis looks forward relative to the text.</p><h4>Rendering UI with Camera Stacking.</h4><p>We want this UI to be visible through everything, often it is annoying when player block it’s visibility.</p><p>For this we can use camera stacking, under the main camera we’ll create a new world space camera(WSUICamera) which will be the overlaying camera, main will be the base camera. In WSUICamera we set the options(also you have to remove audioListener component which Unity adds by default)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*0-Zrl5Xy1xWVJKKesK9K8Q.png" /></figure><p>We add a stack in main camera</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*MqNCk8LLz5zQG6zHjbmF5w.png" /></figure><p>WSUICamera will render only UI layer, so we set our UI objects to this layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*KkTa8u2vPUkCbjl7HCEXNg.png" /></figure><p>In Canvas settings set MainCamera as EventCamera, check the Vertex Color Always In Gamma and remove Graphic Raycaster component as here we don’t have to click on it(we only interact UI by pressing key buttons)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*mELIFenavN9mXG3vmI00uQ.png" /></figure><p>Now it is overlaying on top</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*PQzgrFBYH-0EFTnV0E-_vQ.png" /></figure><h3>Interfaces</h3><p>Before starting Interfaces let’s look at our Interactable code.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Interactable : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _UIContainer;<br><br>    private void Awake()<br>    {<br>        if (_UIContainer != null) _UIContainer.SetActive(false);<br>    }<br><br>    /*<br>    //OnTriggerEnter, collect the item<br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if(other.CompareTag(&quot;Player&quot;))<br>        {<br>            //Modify a player stat<br>            Debug.Log(&quot;add Health&quot;);<br><br>            //Destroy this gameObject<br>            Destroy(gameObject);<br>        }<br>    }<br>    */<br><br>    private void OnTriggerStay(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Player&quot;))<br>        {<br>            //Show UI<br>            if (_UIContainer != null) _UIContainer.SetActive(true);<br>            if (Input.GetKeyDown(KeyCode.E)) Debug.Log(&quot;Interacted&quot;);<br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        //Hide UI<br>        if (_UIContainer != null) _UIContainer.SetActive(false);<br>    }<br>}</pre><p>Now we got this code, can we make it more easier for game designers without manually attaching objects in inspector? Here in our case we can leave it, we only need to attach one object.</p><p>There is also a commented block(OnTriggerEnter) we’ll move it to a new Collectible script.</p><p>If we see OnTriggerStay runs every frame and UI keeps setting active every frame which causes unnecessary calls in runtime. Also we can do the same with input line, now it also keeps calling every frame. With OnTriggerExit everything is ok. Let’s optimize unnecessary set active calls and leave input, in our case it’s fine to go with this.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Interactable : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _UIContainer;<br><br>    private void Awake()<br>    {<br>        if (_UIContainer != null) _UIContainer.SetActive(false);<br>    }<br><br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Player&quot;))<br>            _UIContainer.SetActive(true); //Show UI<br>    }<br><br>    private void OnTriggerStay(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Player&quot;))<br>        {<br>            if (Input.GetKeyDown(KeyCode.E))<br>                Debug.Log(&quot;Interacted&quot;);<br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        //Hide UI<br>        if (_UIContainer != null)<br>            _UIContainer.SetActive(false);<br>    }<br>}</pre><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Collectible : MonoBehaviour<br>{<br>    //OnTriggerEnter, collect the item<br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Player&quot;))<br>        {<br>            //Modify a player stat<br>            Debug.Log(&quot;add Health&quot;);<br><br>            //Destroy this gameObject<br>            Destroy(gameObject);<br>        }<br>    }<br>}</pre><p>A common Unity pattern is to define an IInteractable interface. The player then interacts with <em>anything</em> that implements it, without knowing whether it’s a door, a chest, an NPC or a lever.</p><p>In our scene we have different interactable objects. For example, we have a door and an item, they do different things. The common thing is Player can interact with them pressing E key, for item it increases health, for door it fires the door open animation(also close it if we press it again), we also can switch lights with E key etc. So we’ll create a new C# script and call it IInteractable as a common naming convension(first capital I is for interface).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*DBiHv0fBnQT2TtRJsQgdcA.png" /></figure><p>We replace class with interface and delete : MonoBehaviour, then add a public method wich is going to be called on all interactable type objects. We define what it supposed to do under individual items themselves.</p><p>Let’s create a new PickupItem class</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PickupItem : MonoBehaviour, IInteractable //inherit from IInteractable<br>{<br>    void Start()<br>    {<br>        Debug.Log(&quot;This is a pickup item&quot;);<br>    }<br><br>    public void Interact()//here we define commands when this method calls<br>    {<br>        Debug.Log($&quot;Interacting with {gameObject.name}&quot;);<br>    }<br>}</pre><p>If key pressed Interactable class will call it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioa7n3dbUUpJVbWcneY6Hw.png" /></figure><p>Now in inspector our Item object will have both of these scripts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*QSTb1c_8mEVYaNt3RQjEtQ.png" /></figure><p>If test we see it’s working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*FnqTifB9u_AOlzVtjkdS1Q.png" /></figure><p>Now let’s set up the door interaction. First we setup the UITransform which we add under the DoubleDoorA object with same way as before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwm04OSaFijrLs9LcDtXNw.png" /></figure><p>then we add a trigger collider with interactable script to the door</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ku7aa62c51Xb9xJJd5jfvA.png" /></figure><p>I set the radius 2 to give enough space to interact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*KkzYydXZHrcQ9yZes_cfzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*QzAZFygAmcTY2BXQN-HqUg.png" /></figure><p>If I press E we see the error message, because we have no a defination Interactable for doors. Let’s define it. We’ll create a door script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Door : MonoBehaviour, IInteractable<br>{<br>    private bool _isOpen;<br>    private Animator _anim;<br>    <br>    void Start()<br>    {<br>        _anim = GetComponent&lt;Animator&gt;();<br>    }<br><br>    public void Interact()<br>    {<br>        _isOpen = !_isOpen; //reverse the bool(if false, set it true, if true, set it false)<br>        _anim.SetBool(&quot;IsOpen&quot;, _isOpen);<br>    }<br>}</pre><p>We already have an animator controller in assets, we need to add an aninmator component to the Door and attach it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*UeCHO7RUecNYYU-ai-7Yuw.png" /></figure><p>We can set Entry default state as Door_Close if we want. We also have a bool controller ready</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*xskzVTtLP5VC6gUC1Y0T-w.png" /></figure><p>We aslo attach the door script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*0kgiUDb9cI4OWsUmTUTEew.png" /></figure><p>Let’s test it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*xI5Eij1vu_JJ5wmqRO-PtQ.png" /></figure><p>Now it’s opening and closing, but input sometimes doesn’t reacting because of OnTriggerStay(it happens in fixed time steps, not every frame), let’s fix it.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Interactable : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _UIContainer;<br>    //referencing for IInteractable, because we use it here for all type interactables(pickups, doors, etc.)<br>    private IInteractable _interactable;<br>    private bool _isInteractable;<br><br>    private void Awake()<br>    {<br>        if (_UIContainer != null) _UIContainer.SetActive(false);<br>        _interactable = GetComponent&lt;IInteractable&gt;();<br>        _isInteractable = false;<br>    }<br><br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Player&quot;))<br>        {<br>            if (_UIContainer != null)<br>                _UIContainer.SetActive(true); //Show UI<br>            _isInteractable = true;<br>        }<br>    }<br><br>    private void Update()<br>    {<br>        if (_isInteractable &amp;&amp; Input.GetKeyDown(KeyCode.E))<br>        {<br>            _interactable.Interact();<br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        if(other.CompareTag(&quot;Player&quot;))<br>        {<br>            //Hide UI<br>            if (_UIContainer != null)<br>                _UIContainer.SetActive(false);<br>            _isInteractable = false;<br>        }<br>    }<br>}</pre><p>So this is the fixed Interactable script using update method, here we don’t need OnTriggerStay no more.</p><p>If you want to see private bools in inspector without typing [SerializeField] you can set Inspector to Debug mode, then we can see how bool is changing in play mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*BIaG46BfcBuMFy5USDXfYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*dOWgZUi88gy6-ycNszPTpw.png" /></figure><p>Then after testing switch back to normal. I tested, with update it works better.</p><h3>Creating the Light Interactable</h3><p>Light is going to be another interactable. Remember when we worked on Door or item we added components in scene object, not inside a prefab editor, so we got these overrides on them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*fvlsuN1Yzi-La8WHGYtyzw.png" /></figure><p>Here we got lights as prefabs in our scene, in here we are going to go with another way relative to prefab editing system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5ykG8LbZgv5UI4z0dLO7A.png" /></figure><p>These prefabs are not in final step, let’s modify them. These changes must be done in prefab editor, because some overrides can cause some linking problems, especially if you have nested prefabs. If you select one of them in scene you see in inspector which prefab is this object using, find it in assets and double click on that prefab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*Ku7ZURSo0aho2wjc8A5Ypw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8qPsVZR2u6tQt0CElzn-Q.png" /></figure><p>Let’s add a sphere trigger collider first. We also add interactable script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*ttitIeJ5dp5evOC9cJYy1w.png" /></figure><p>It will ask you to attach UIContainer. We add UITransform here as a child</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*L7RD02urOcaic7GJ9k8t6g.png" /></figure><p>In scene we’ll drag this UICantainer to Interactable inspector space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*w5mUtM_3CGn-IsY5bcO45w.png" /></figure><p>You can see it marked blue that means an override, because we did change in scene. Here it shows us this change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*FhNOeknqnCE2wVbBJT2tmw.png" /></figure><p>If we apply this, only this UICantainer will be attached in inspector. Every prefab in scene gets it’s own child UIContainer. You can check Light B. A smart system by Unity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*1Yxkrl_zR-e1reE1jfmIeg.png" /></figure><p>Let’s modify UITransform by adding LookAt script inside it’s prefab editor. You can switch to it’s editor also by clicking this arrow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*g4d73yC1nkP7-FdL5511Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*TB49LMpmhBTkhTlkZrCRzw.png" /></figure><p>And here we have to attach main camera, but it doesn’t exist in this editor. We’ll do this via code. In Unity there is a keyword to detect it Camera.Main. With this we free game designers manually attaching cameras to all UITransform elements in scene making their life easier.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class UILookAt : MonoBehaviour<br>{<br>    private Transform _cameraTransform;<br><br>    private void Start()<br>    {<br>        _cameraTransform = Camera.main.transform;<br>    }<br><br>    private void LateUpdate()<br>    {<br>        //LookAt method to change the orientation of the UI by Y axis<br>        //object looks to the target by it&#39;s face(z axis)<br>        transform.LookAt(_cameraTransform);<br>    }<br>}</pre><p>Now, let’s place it above the light and test it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H12NJAagpPw4y7xb5Mh70A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*MCRmTq7fVMBUcLpTNYaSkQ.png" /></figure><p>We see it’s working fine. It must work because by default existing MainCamera in the scene always tagged as MainCamera</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*sSu4isSF8eiisJ6RITO9ZQ.png" /></figure><p>Now designer can add another light prefab variants and no need to attach anything in inspector.</p><p>Now we want to switch it on and off, if you look at this prefab in inspector it has 2 materials: base and emissive. We need to control emissive, in meshRenderer we see it is attached to slot 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*5ukOPuWb1M5CBKW9b1i9Fg.png" /></figure><p>Let’s create a new script ToggleLight</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*pVQwHZI_wpTZNHjrZjd1uA.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class ToggleLight : MonoBehaviour, IInteractable<br>{<br>    //reference to the material via the meshRenderer<br>    private Material _emissiveMaterial;<br>    [SerializeField] private bool _isOn;<br>    [SerializeField] private float _emissionPower = 5f;<br>    <br>    private void Start()<br>    {<br>        _emissiveMaterial = GetComponent&lt;MeshRenderer&gt;().materials[1];<br>        //Create some functionality for the designer(must it be on at start?)<br>        if (_isOn)<br>            _emissiveMaterial.SetColor(&quot;_EmissionColor&quot;, Color.white * _emissionPower);<br>        else<br>            _emissiveMaterial.SetColor(&quot;_EmissionColor&quot;, Color.black);<br>    }<br><br>    public void Interact() //Toggle light on/off via emissive material<br>    {<br>        if (_isOn)<br>            _emissiveMaterial.SetColor(&quot;_EmissionColor&quot;, Color.white * _emissionPower);<br>        else<br>            _emissiveMaterial.SetColor(&quot;_EmissionColor&quot;, Color.black);<br>        _isOn = !_isOn;<br>    }<br>}</pre><p>Here designer sets wich will be on at start of the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7FS44Phj97SMg6Qz8kCKg.png" /></figure><h3>More Control Over Doors</h3><p>Here we are going to modify the door class by adding lock/unlock functions. Here I commented what we are going to add</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*FzIGuF6T3LhiPqC2GQzwiQ.png" /></figure><p>In scene I’ll work with another door, so I have to override all changes from previous door.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NL_GC5nOfq5Jx4u_OULwqg.png" /></figure><p>then check if UIContainer is it attached it’s own UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*sVqqpp8duP48csTjGmxJRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*h764n4Ztla5AMoYHd8m89g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwIXSSvPPG4g_KbZqcd1xg.png" /></figure><p>we got this log, so it’s going fine, let’s work with terminal. We are going to make this code as much flexible as possible, it might unlock not only one door, maybe several doors, maybe elevator or something else, we want designer can play with it, connect with any objects without any code modifications just setting them in inspector. Here what we want to do in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*qk-3_0PPw_MztSfdTH1gDg.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Terminal : MonoBehaviour, IInteractable<br>{<br>    //get target reference<br>    [SerializeField] private GameObject[] _targets;<br>    //create a reference to power up the terminal(with electricity)<br>    [SerializeField] private bool _isPowered;<br><br>    //On Interact<br>    public void Interact()<br>    {<br>        //get all of the targets<br>        //foreach target<br>        foreach(GameObject _target in _targets)<br>        {<br>            //activate those targers via a new method<br>            if(_target.TryGetComponent&lt;IInteractable&gt;(out IInteractable interactable))<br>            {<br>                Debug.Log(_target.name + &quot; is powered up!&quot;);<br>            }<br>        }<br>    }<br><br><br>    //if powered off, then activate the terminal</pre><p>if(_target.TryGetComponent&lt;IInteractable&gt;(out IInteractable interactable)) is new here, what it means?</p><ul><li><strong>_target</strong> is a GameObject or Component (usually whatever the player is looking at or touching).</li><li><strong>TryGetComponent&lt;IInteractable&gt;</strong> asks Unity to look on that GameObject for a component of type IInteractable. Because IInteractable is an interface, any script that implements it counts, whether it’s a Door, Chest, NPC, etc.</li><li><strong>out IInteractable interactable</strong> declares a new variable named interactable. If a matching component is found, Unity puts it into this variable.</li><li><strong>The method returns </strong><strong>bool</strong>: true if a component was found, false if not. That’s why it can go directly inside if (...).</li></ul><p>Let’s attach scripts on that object(terminal), add target make it powered for now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSpFQ4PYE29s4n9JtMakcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIJDJ6uHdnfK_7P-b-CIFQ.png" /></figure><p>So the terminal is set up, it gives us message that doorB is powered, but door actually isn’t unlocked, we didn’t connect these two classes, they work independently. For this we need extend our interactable interface.</p><p>As this activation function is common for all IInteractable objects in scene(doors, elevators terminals etc.) we’ll define a new activate method inside IInteractable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*cnDA8pU9HJPvwz921TpmcA.png" /></figure><p>Now all classes that inherits this interface will require to be exist this method inside it at least an empty one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*zqgduV2wlR3VYM3T2X16Sg.png" /></figure><p>In terminal it will activate as power up by generator, we’ll make it later.</p><p>In toggleLight we don’t need it, so I left it empty, but some day if we need we can add this functionality</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*UzEoplukY01jXe5Yd8UVew.png" /></figure><p>Now we need set it in door, but first we call it inside interact() of terminal, so it will apply to all Doors in scene.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*IDHYJohbNcmGrvdvf9zG1g.png" /></figure><p>then in door it makes door unlocked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*iZnKJupWz8cnQrwbo1-lkA.png" /></figure><p>It works, you can check it.</p><h4>Creating the Door Control Panel.</h4><p>Now we need door panel to make door state(lock/unlock) visible. We already have for this prefabs. Let’s place them under DoubleDoor as child.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPz03o8vTBfn_aDSBNMYJQ.png" /></figure><p>We’ll override it to make apply it dor all DoubleDoor prefabs.</p><p>Then we implement this in Door class</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Door : MonoBehaviour, IInteractable<br>{<br>    private bool _isOpen;<br>    private Animator _anim;<br>    //reference to toggle the door lock<br>    [SerializeField] private bool _isLocked;<br>    [SerializeField] private GameObject[] _doorPanels;<br>    <br>    void Start()<br>    {<br>        _anim = GetComponent&lt;Animator&gt;();<br>        if (_isLocked)<br>        {<br>            _doorPanels[0].SetActive(true);<br>            _doorPanels[1].SetActive(false);<br>        }<br>        else<br>        {<br>            _doorPanels[0].SetActive(false);<br>            _doorPanels[1].SetActive(true);<br>        }<br>    }<br><br>    public void Interact()<br>    {<br>        //if the door is locked, stay locked and print a message that tells the player what to do<br>        //if the door is unlocked, then open the door<br>        if (!_isLocked)<br>        {<br>            _isOpen = !_isOpen; //reverse the bool(if false, set it true, if true, set it false)<br>            _anim.SetBool(&quot;IsOpen&quot;, _isOpen);<br>        }<br>        else<br>        {<br>            Debug.Log(&quot;Locked! Check the terminal&quot;);<br>        }<br>    }<br><br>    public void Activate()<br>    {<br>        UnlockDoor();//unlock the door<br>    }<br><br>    private void UnlockDoor()<br>    {<br>        _isLocked = false;<br>        _doorPanels[0].SetActive(false);<br>        _doorPanels[1].SetActive(true);<br>    }<br>}</pre><p>then we set them in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*R8JZn5_6B021pWDIXcA0yg.png" /></figure><p>Is Locked is bold, don’t override it, it will be different for all doors.</p><h3>Physics Based Pressure Plates</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*uFcqEGvIS7saczwqWzQSRQ.png" /></figure><p>We got here a PressurePad and a box, Player have to push this box onto this pad, then it will be pressed. For this we have to add trigger collider which is going to set isPressed to true, also in box object rigidbody mass have to be enough, then we need a spring joint to make this pad pressable, in player, check can push and set strength to 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*utGo48tSGZf8JSNIibMC7w.png" /></figure><p>This is a trigger collider, we set it in base object of pressurePad</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-5ClxWFuf8GYv_4aDpVlw.png" /></figure><p>Now let’s set up spring joint. We add it on pad object, before this we add a rigidbody to base and make it static planted to ground object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*JX7yazzGPclprFihx-y7Ew.png" /></figure><p>Then we add spring joint to pad, there also appers rigidbody with it, in rigidbody we set freeze constraints, we want pad to move only up/down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*9MG9y1Y3Ai__NJ6wcC9NEA.png" /></figure><p>Then we set spring joint, add base as connected body</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*EpXh0ZFbtsCdXPfnOo0B_g.png" /></figure><p>Anchor and Connected Anchor we set looking in play mode, spring in cases like this must be about 250. here are anchors in scene, 1 is anchor, 2- connected anchor, anchor is higher to make it move up by it’s own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*CtOPMOodusgq_bkbCgNlgQ.png" /></figure><p>We have a large crate with rigidbody, which player have to move it onto the pad to push it, it’s mass we set 10, which is enough to press it. In Player I also set push layer(new layer called PhysicsObjects)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*BELWI_UUwbkLB_2NOmJsFQ.png" /></figure><p>then set crate object to this layer, so Player can push it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*SCjeVDTeNF99BsS7OzibHQ.png" /></figure><p>Time to test it, so it’s working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSVccg6VmXb2KwOp7Yl8bg.png" /></figure><p>Player can’t stand on it and push it without crate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*l0En18MJ9UXtHFODSn1Wmg.png" /></figure><p>To make a puzzle you can add more crates and only one of them is going to be heavy enough to push it, so Player have to find that crate.</p><p>So let’s make a pad functionality, what we are going to unlock with pushing it. But first we correct thing, I added trigger collider to base by mistake, I’ll remove it from there and add this collider to main object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZo32jW4fWfmr0EK36rXUw.png" /></figure><p>We create a new script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*eLvGK6BPzuvB1rzgNUuP7A.png" /></figure><p>We are going to unlock the next door with it.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PressurePad : MonoBehaviour<br>{<br>    //reference to the target<br>    [SerializeField] private GameObject[] _targets;<br>    [SerializeField] private bool _isPressed;<br><br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if(other.CompareTag(&quot;Pad&quot;))<br>        {<br>            //Activate the target through a bool value<br>            Debug.Log(&quot;Unlocked&quot;);<br><br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Pad&quot;))<br>        {<br>            //Deactivate the target through a bool value<br>            Debug.Log(&quot;Locked&quot;);<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*otxtwHdvcC9MJYWMs9OxqQ.png" /></figure><p>We have this result after we tested. This is because the pad is jumping before to get to static position. To fix it wa can make trigger collider bigger height, so it doesn’t exit when it jumps. Actually you can keep this collider as it is, because the crate also swing by it’s own.</p><p>Now let’s connect them through IInteractable Activate(), but we got here deactivate function also that must make isLocked to true. We can use Activate() method for both, calling it using with bool option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*ST3Hg3h4Ppcc0OlfU8beQA.png" /></figure><p>Now we have to coorect all scripts where it was called.</p><p>In terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*6vNGzdNCfNueIIPs0MS2ig.png" /></figure><p>In ToggleLight, PickupItem, PressurePad is empty</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*5sBM8cgVIfXOBCuH0Vpecw.png" /></figure><p>In Door also corrected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*e52Lr27kb6612i2lsdM0VQ.png" /></figure><p>And pressurePad is done</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PressurePad : MonoBehaviour<br>{<br>    //reference to the target<br>    [SerializeField] private GameObject[] _targets;<br>    [SerializeField] private bool _isPressed;<br><br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if(other.CompareTag(&quot;Pad&quot;))<br>        {<br>            _isPressed = true;<br>            foreach (GameObject _target in _targets)<br>            {<br>                //Activate the target through a bool value<br>                if (_target.TryGetComponent&lt;IInteractable&gt;(out IInteractable _interactable))<br>                    _interactable.Activate(_isPressed);<br>            }<br>        }<br>    }<br><br>    private void OnTriggerExit(Collider other)<br>    {<br>        if (other.CompareTag(&quot;Pad&quot;))<br>        {<br>            _isPressed = false;<br>            foreach (GameObject _target in _targets)<br>            {<br>                //Deactivate the target through a bool value<br>                if (_target.TryGetComponent&lt;IInteractable&gt;(out IInteractable _interactable))<br>                    _interactable.Activate(_isPressed);<br>            }<br>        }<br>    }<br><br>    public void Activate(bool _isActive) { }<br>}</pre><p>You can test it, it works fine, if I push the crate away, it locked again. This affects only the door C because we only added Door C to targets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*Q0rWmCwqYZqhUkpXcqnMgw.png" /></figure><p>Very comfortable and flexible system by using IInteractable.</p><h3>Interactable Chest And Loot</h3><p>Let’s set it up similar with door.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*r2q8YkfFGNBUrlTq0mu8RQ.png" /></figure><p>Chest animator is already prepared as like for Door, also for this I created a new script Chest and attached.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Chest : MonoBehaviour, IInteractable<br>{<br>    private bool _isOpen;<br>    private Animator _anim;<br>    [SerializeField] private bool _isLocked;<br><br>    private void Start()<br>    {<br>        _anim = GetComponent&lt;Animator&gt;();<br>    }<br><br>    //Use IInteractable to open the chest<br>    public void Interact()<br>    {<br>        if(!_isLocked)<br>        {<br>            _isOpen = !_isOpen;<br>            _anim.SetBool(&quot;IsOpen&quot;, _isOpen);<br>            //spawn loot<br>        }<br>    }<br><br>    public void Activate(bool _isActive) { }//activate method to match interface signature<br>}</pre><p>Now let’s add spawn loot function, best practice is to spawn it using separate class SpawnLoot. We can do the loop spawning using popup interface with items, player can take them by dragging those itmes outside the box like traditional RPG games. In 3rd Person games like our better to make the loot to pop out the chest to somewhere where it is aviable to interact and pick it up.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class SpawnLoot : MonoBehaviour<br>{<br>    //List of Items<br>    [SerializeField] private List&lt;GameObject&gt; _lootItem = new List&lt;GameObject&gt;();<br><br>    //Random range of items spawning from chest<br>    [SerializeField] [Range(1, 19)] private int _minNumber = 1;<br>    [SerializeField] [Range(2, 20)] private int _maxNumber = 5;<br><br>    //Reference to a spawn point in chest<br>    [SerializeField] private Transform _spawnPoint;<br><br>    //Check if chest has been interacted with<br>    private bool _isCollected = false;<br>    //don&#39;t spawn loot if interacted with once, is public to be able to set from Chest<br>    public bool _isSpawned = false;<br>    <br>    private void Update()<br>    {<br>        if(_isSpawned &amp;&amp; !_isCollected)//spawned, but not collected yet<br>        {<br>            _isSpawned = false;<br>            Loot();<br>        }<br>    }<br><br>    //instantiate the loot<br>    private void Loot()<br>    {<br>        Debug.Log(&quot;Spawn loot!&quot;);<br>        int number = Random.Range(_minNumber, _maxNumber);<br>        StartCoroutine(CreateLoot(number));<br>    }<br><br>    //use a coroutine to have items spawn one after another<br>    IEnumerator CreateLoot(int number)<br>    {<br>        yield return new WaitForSeconds(1f);<br><br>        for(int i = 0; i &lt; number; i++)<br>        {<br>            GameObject loot = Instantiate(_lootItem[Random.Range(0, _lootItem.Count)], _spawnPoint.position, Quaternion.identity);<br>            yield return new WaitForSeconds(0.2f);<br>        }<br>    }<br>}</pre><p>Here is a SpawnLoot script, we set _isSpawned to true</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*_hYpgPCP9NOK2eIdkduv6Q.png" /></figure><p>SpawnLoot in update checks for _isSpawn every frame, so after interact it calls Loot(). Let’s set up the inspector. As loot I created a simple cube object as prefab. created an empty spawnPoint under ChestVariant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*zNuYzLUi2hq2KSgtIYMNyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*JL7EDg3G7Vyhu1xM4ULM3Q.png" /></figure><p>Now it is instantiating. Also we got the message one time that shows it spawned once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*ym7QXTcMQx6aVQSyJYhhTA.png" /></figure><p>Now we want this loot to be dropped out of the chest using physics. We’ll create for this a new script LootDrop.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class LootDrop : MonoBehaviour<br>{<br>    //reference to a rigidbody component<br>    private Rigidbody _rb;<br>    [SerializeField] private float _strength = 5f;<br><br>    private void Start()<br>    {<br>        _rb = GetComponent&lt;Rigidbody&gt;();<br>        //use physics to push the loot item out of the chest<br>        _rb.AddForce(new Vector3(Random.Range(-2f, 2f), _strength, Random.Range(-2f, 2f)), ForceMode.Impulse);<br>        //use physics to spin the item out of the chest<br>        _rb.AddTorque(new Vector3(Random.Range(-1f, 1f), _strength, Random.Range(-1f, 1f)), ForceMode.Impulse);<br>    }<br>}</pre><p>And attach it to Loot prefab, also add a rigidbody .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*jDvg_d6vn5wooZiJ_FrE6w.png" /></figure><p>I tested it, it spawns again if I close the chest, so to prevent this I added one more bool check</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiCM7w9kDtNTrY_lptFMlg.png" /></figure><p>Next we need inventory manager to interact with spawned items. Player is going to work with Inventory during the game any time, on every level, so the Inventory manager is a global game object. They might be a singleton, static or have it’s own instance. In it we are going to do this for start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*8r3yhgoPcBr7j6n99zL14Q.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class InventoryManager : MonoBehaviour<br>{<br>    //Reference to the InventoryManager as a static variable<br>    public static InventoryManager Instance; //static means global which accessible from anywhere.<br><br>    //Create a list of all inventory items<br>    public List&lt;AllItems&gt; _inventoryItems = new List&lt;AllItems&gt;();<br>    <br>    //Items in an enum<br>    public enum AllItems<br>    {<br>        //four items(keykards)<br>        KeycardA,<br>        KeycardB,<br>        KeycardC,<br>        KeycardD,<br>    }<br><br>    private void Awake()<br>    {<br>        //Get a single instance of the InventoryManager(this)<br>        Instance = this;<br>    }<br><br>    //Add collected items to the inventory list<br>    public void AddItems(AllItems item)<br>    {<br>        if(!_inventoryItems.Contains(item))//If the item is not in the list<br>        {<br>            _inventoryItems.Add(item);//Add the item<br>        }<br>    }<br><br>    //Remove collected items to the inventory list<br>    public void RemoveItems(AllItems item)<br>    {<br>        if (_inventoryItems.Contains(item))//If the item is in the list<br>        {<br>            _inventoryItems.Remove(item);//Remove the item<br>        }<br>    }<br>}</pre><p>Next is to create a LootItem script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class LootItem : MonoBehaviour, IInteractable<br>{<br>    //Reference to our InventoryManager item type<br>    [SerializeField] private InventoryManager.AllItems _itemType;<br><br>    //Interact with the item<br>    public void Interact()<br>    {<br>        //Add this item to the inventory manager<br>        InventoryManager.Instance.AddItems(_itemType);<br>        //Destroy gameObject<br>        Destroy(gameObject);<br>    }<br><br>    //Add Activation code<br>    public void Activate(bool _isActive) { }<br>}</pre><p>Here is how we add items to enums. Here we interact with this look item through IInteractable. We attach it to our Loot prefab, inside it we replace cube to already prepared card model with collider, and set rigidbody Collision Detection to Continuous Dynamic as it is enough small object to make harder physics to detect it and it might fall through floor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNj9aC_9zT9zdfWmQ8VPuw.png" /></figure><p>Also you can name it as Keycard instead of Loot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*jHR1zwA1AmjUN82Cp85n5A.png" /></figure><p>Now it’s popping out the chest, we need to add elements to interact with it as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10d0I_65HclDvm5bGwzL3Q.png" /></figure><p>Now it’s here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*ObLWYI1pe7RtoAHHnegDEQ.png" /></figure><p>We have NullReferenceException when we press E</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*n7Y5u7D_Qg4I4I7qaxsCzQ.png" /></figure><p>To fix it we need an object InventoryManager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*K_epnLSY__39QecAdLxAAQ.png" /></figure><p>We leave this list empty as Interact() inside LootItem is going to add all interacted loot items here during the game</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*GDk8Vcj6Cisb7-wwt_1isg.png" /></figure><p>Now we can also make our pickup object(from earlier tasks) to be collected into this inventory. For this we define a new type of item in InventoryManager Enum</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*VveoXwCdTLbjufa8z5CS4A.png" /></figure><p>Then add some lines in pickupItem class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*OuixHzGBBqopH1jl1F1w3g.png" /></figure><p>and set it in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*6P-fwalGlxF2C42doKJ2rg.png" /></figure><p>Now in playMode if we pick it up add to our InventoryManager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*mukMrfBFCs9COb8J_7OQHQ.png" /></figure><p>Now we are going to use Keycard to unlock the door. We need to add this functionality to our Door.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*3Zbn9tXxpXzr-5ThsYIQpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*_AIfhs6fuX10QyYETFWYaQ.png" /></figure><p>Some Doors might be broken, or not interactable(just a prop object). Keep in mind, in these cases designer must let Player to easy recognize that this door is never going to open, making it’s visibility different, for example, broken, unpowered or rusty or give Player this kind of message.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Door : MonoBehaviour, IInteractable<br>{<br>    private bool _isOpen;<br>    private Animator _anim;<br>    //reference to toggle the door lock<br>    [SerializeField] private bool _isLocked;<br>    [SerializeField] private GameObject[] _doorPanels;<br><br>    //Designer need the ability to require an item for the door(keycard)<br>    [SerializeField] private bool _requiresItem;<br>    //Reference to the required item<br>    [SerializeField] private InventoryManager.AllItems _requiredItem;<br>    <br>    void Start()<br>    {<br>        _anim = GetComponent&lt;Animator&gt;();<br>        if (_isLocked)<br>        {<br>            _doorPanels[0].SetActive(true);<br>            _doorPanels[1].SetActive(false);<br>        }<br>        else<br>        {<br>            _doorPanels[0].SetActive(false);<br>            _doorPanels[1].SetActive(true);<br>        }<br>    }<br><br>    public void Interact()<br>    {<br>        if (!_isLocked)//if the door is unlocked, then open the door<br>        {<br>            _isOpen = !_isOpen; //reverse the bool(if false, set it true, if true, set it false)<br>            _anim.SetBool(&quot;IsOpen&quot;, _isOpen);<br>        }<br>        else //if the door is locked, stay locked and print a message that tells the player what to do<br>        {<br>            //Check if door requires an item<br>            if(_requiresItem)<br>            {<br>                //Check if we have the required item<br>                if (HasRequiredItem(_requiredItem))<br>                    Activate(true); //Unlock the door(Activate)<br>                else<br>                    Debug.Log(&quot;Check the Terminal!&quot;); //If we don&#39;t have the required item, check the terminal<br>            }<br>            Debug.Log(&quot;Locked! Check the terminal&quot;);//If it doesn&#39;t require the item<br>        }<br>    }<br><br>    public void Activate(bool _isActive)<br>    {<br>        UnlockDoor(_isActive);//lock/unlock the door<br>    }<br><br>    private void UnlockDoor(bool _isActive)<br>    {<br>        _isLocked = !_isActive;<br>        if (_isLocked)<br>        {<br>            _doorPanels[0].SetActive(true);<br>            _doorPanels[1].SetActive(false);<br>        }<br>        else<br>        {<br>            _doorPanels[0].SetActive(false);<br>            _doorPanels[1].SetActive(true);<br>        }<br>    }<br><br>    //Method to check if we have the required item<br>    public bool HasRequiredItem(InventoryManager.AllItems _itemRequired)<br>    {<br>        if (InventoryManager.Instance._inventoryItems.Contains(_itemRequired))<br>            return true;<br>        else<br>            return false;<br>    }<br>}</pre><p>This is a modified script. Let’s test it on DoorD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*pqvqG05L18Xdkh8ZpoA6Yw.png" /></figure><p>We add KeycardD(copied KeycardA, but defined as D) to chest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*-vrJ01RZBnbUDya2hEGMfg.png" /></figure><p>Tested, it works good! Next is Puzzle Mechanics — Power Core, this topic has already become quite big, I thing better to continue it in the next topic…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0224d078b7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GME 302: Physics In Unity. Part-2]]></title>
            <link>https://medium.com/@yanvar103/gme-302-physics-in-unity-part-2-686c9d9f577a?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/686c9d9f577a</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 12:25:46 GMT</pubDate>
            <atom:updated>2026-10-02T12:25:46.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trajectories</h3><p>For what we need trajectories, Let’s see it in example. Here we are going to launch a cube object(prefab) from Launcher into the portal through the hole in glass wall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*JAfl4Od0ioBaKj2Vy-IvIQ.png" /></figure><p>Let’s create a prefab that will be launched. We drag fbx file from project window to scene, modify it by adding some components as collider, rigidbody and script. Then we drag it into new Prefabs folder in project window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*xmaKsvcwJ043nqt7NCkz6w.png" /></figure><p>As we didn’t unpack the fbx in scene, we still have a connection between fbx and prefab, if we change fbx file it will be auto updated also in prefab. Don’t forget to set it’s tag as LabItem!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*shapO-qE9k4y-toRQfKBDw.png" /></figure><p>Let’s type a script for this prefab behaviour</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class AirmailPackage : MonoBehaviour<br>{<br>    //get a reference to the rigidbody<br>    private Rigidbody _rb;<br><br>    private void Awake()<br>    {<br>        _rb = GetComponent&lt;Rigidbody&gt;();<br>    }<br><br>    //create a method that will pass in velocity/power value from launcher<br>    public void Init(Vector3 velocity)<br>    {<br>        //apply force to the gameObject<br>        _rb.AddForce(velocity, ForceMode.Impulse);<br>    }<br>}</pre><p>And we create a new script for launcher that will instantiate this prefab. Here is a pseudocode for it</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Launcher : MonoBehaviour<br>{<br>    //create a reference to the package prefab<br>    //reference to the amount of force to apply<br><br><br>    // Update is called once per frame<br>    void Update()<br>    {<br>        //get the input from player<br>        //instantiate the packagePrefab and apply the force<br>        //tell package where to instantiate<br>        //call the init function from the package<br>    }<br>}</pre><p>And the script itself</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Launcher : MonoBehaviour<br>{<br>    //create a reference to the package prefab<br>    [SerializeField] private AirmailPackage _airmailPackagePrefab;<br><br>    //reference to the amount of force to apply<br>    [SerializeField] private float _force = 10f;<br><br>    [SerializeField] private LabComplete _labComplete;<br><br>    // Update is called once per frame<br>    void Update()<br>    {<br>        //get the input from player<br>        if (Input.GetKeyDown(KeyCode.Space))<br>        {<br>            //instantiate the packagePrefab and apply the force<br>            var _spawned = Instantiate(_airmailPackagePrefab, transform.position, transform.rotation);<br>            <br>            //tell package where to instantiate<br>            _spawned.transform.parent = transform.root;<br><br>            //call the init function from the package<br>            _spawned.Init(transform.forward * _force);<br><br>            _labComplete.CheckCriteria();<br>        }<br>    }<br>}</pre><p>We already have LabComplete class created for this course, we just need to call it here, in inspector attach the portal object wich has attached this script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*fVO3uMka5yNRcLYTriupBw.png" /></figure><p>Here to launch properly in game mode better to see the trajectory to correct the turret angle. So now we need a trajectory, and for this we need a simulated physics scene.</p><h4>Creating Simulated Physics Scene</h4><p>In Unity we have a multi scene capability. Let’s check scene manager in unity API</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.SceneManager.html">SceneManager</a></p><p>here inside <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.SceneManager.html">SceneManager</a>.CreateScene there is <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.CreateSceneParameters.html">SceneManagement.CreateSceneParameters</a> <strong>parameters</strong></p><p>And in it there is <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.CreateSceneParameters.html">CreateSceneParameters</a>.localPhysicsMode</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.LocalPhysicsMode.html">LocalPhysicsMode</a></p><blockquote>Description: Provides options for 2D and 3D local physics.</blockquote><blockquote>By default, when a <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.Scene.html">Scene</a> is created or loaded, any 2D or 3D physics component added to a GameObject within the Scene is added to the default physics Scene. Each <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.Scene.html">Scene</a> however has the ability to create and own its own (local) 2D and/or 3D physics Scene. This option can be used when creating or loading a Scene to specify whether a 2D and/or 3D physics Scene should be created.</blockquote><blockquote>When a <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.Scene.html">Scene</a> creates its own 2D and/or 3D physics Scene, the lifetime of the physics Scene(s) is the same as the <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.Scene.html">Scene</a> i.e. if the <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/SceneManagement.Scene.html">Scene</a> is destroyed/unloaded then so are any created physics Scenes.</blockquote><p>So, now let’s create a new script SimulatedPhysics. It will create us new simulated scene.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.SceneManagement;//using this namespace we get access to Unity sceneManagement classes.<br><br>public class SimulatedPhysics : MonoBehaviour<br>{<br>    //cretae a reference for the new simulated scene<br>    private Scene _simulatedScene;<br>    //create a reference to the physics scene of the simulated scene<br>    private PhysicsScene _physicsScene;<br>    //create a reference to the lab parent<br>    [SerializeField] private Transform _labParent;<br><br>    <br>    // Start is called before the first frame update<br>    void Start()<br>    {<br>        //set the lab parent reference<br>        _labParent = transform.parent.root;<br>        //call the new Create Simulaed Physics Scene method<br>        CreateSimulatedPhysicsScene();<br>    }<br><br>    //create a new method for creating the simulated physics scene<br>    void CreateSimulatedPhysicsScene()<br>    {<br>        //set the new created scene to the simulated scene reference using CreateScene method from SceneManager class<br>        _simulatedScene = SceneManager.CreateScene(&quot;SimulatedPhysics&quot;, new CreateSceneParameters(LocalPhysicsMode.Physics3D));<br>        //set the new physics scene from the simulated scene<br>        _physicsScene = _simulatedScene.GetPhysicsScene();<br><br>        //move gameobjects to the new simulated physics scene<br><br>    }<br>}</pre><p>We’ll attach it to our launcher object, in inspector we’ll also attach our Lab10 as _labParent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*EUPAmPAtDahobYiCll0ttw.png" /></figure><p>We see it created us this scene in play mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*XDw_5z57Jni5I6fg8WL3OA.png" /></figure><p>Let’s move the objects inside lab10 to that scene</p><p>we create a reference of these objects that has tagged as Obstacle which are inside lab10 then instantiate them in new simulatedPhysics scene with disabled mesh renderer</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.SceneManagement;//using this namespace we get access to Unity sceneManagement classes.<br><br>public class SimulatedPhysics : MonoBehaviour<br>{<br>    //cretae a reference for the new simulated scene<br>    private Scene _simulatedScene;<br>    //create a reference to the physics scene of the simulated scene<br>    private PhysicsScene _physicsScene;<br>    //create a reference to the lab parent<br>    [SerializeField] private Transform _labParent;<br><br>    <br>    // Start is called before the first frame update<br>    void Start()<br>    {<br>        //set the lab parent reference<br>        _labParent = transform.parent.root;<br>        //call the new Create Simulaed Physics Scene method<br>        CreateSimulatedPhysicsScene();<br>    }<br><br>    //create a new method for creating the simulated physics scene<br>    void CreateSimulatedPhysicsScene()<br>    {<br>        //set the new created scene to the simulated scene reference using CreateScene method from SceneManager class<br>        _simulatedScene = SceneManager.CreateScene(&quot;SimulatedPhysics&quot;, new CreateSceneParameters(LocalPhysicsMode.Physics3D));<br>        //set the new physics scene from the simulated scene<br>        _physicsScene = _simulatedScene.GetPhysicsScene();<br><br>        //foreach object tagged as obstacle in labParent    <br>        foreach(Transform obsacle in _labParent)<br>        {<br>            if(obsacle.CompareTag(&quot;Obstacle&quot;))<br>            {<br>                //create a reference for the simulaed obstacles and instantiate the new obstacles which has no unneccessary components<br>                var simulatedObstacle = Instantiate(obsacle.gameObject, obsacle.position, obsacle.rotation);<br>                //get the meshRenderer of each obstacle and disable it<br>                if(simulatedObstacle.GetComponent&lt;Renderer&gt;() != null)<br>                {<br>                    simulatedObstacle.GetComponent&lt;Renderer&gt;().enabled = false;<br>                }<br>                //move gameobjects to the new simulated physics scene<br>                SceneManager.MoveGameObjectToScene(simulatedObstacle, _simulatedScene);<br>            }<br>        }<br>    }<br>}</pre><p>So here we see it created as we wanted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*SWFG1oliIi2mOEUTdhsg1g.png" /></figure><p>Now we need to create line renderer trajectory in new method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*NnQPCul43WhRfubpbp-Q6Q.png" /></figure><p>Here is a code</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.SceneManagement;//using this namespace we get access to Unity sceneManagement classes.<br><br>public class SimulatedPhysics : MonoBehaviour<br>{<br>    //cretae a reference for the new simulated scene<br>    private Scene _simulatedScene;<br>    //create a reference to the physics scene of the simulated scene<br>    private PhysicsScene _physicsScene;<br>    //create a reference to the lab parent<br>    [SerializeField] private Transform _labParent;<br><br>    <br>    // Start is called before the first frame update<br>    void Start()<br>    {<br>        //set the lab parent reference<br>        _labParent = transform.parent.root;<br>        //call the new Create Simulaed Physics Scene method<br>        CreateSimulatedPhysicsScene();<br>    }<br><br>    //create a new method for creating the simulated physics scene<br>    void CreateSimulatedPhysicsScene()<br>    {<br>        //set the new created scene to the simulated scene reference using CreateScene method from SceneManager class<br>        _simulatedScene = SceneManager.CreateScene(&quot;SimulatedPhysics&quot;, new CreateSceneParameters(LocalPhysicsMode.Physics3D));<br>        //set the new physics scene from the simulated scene<br>        _physicsScene = _simulatedScene.GetPhysicsScene();<br><br>        //foreach object tagged as obstacle in labParent    <br>        foreach(Transform obsacle in _labParent)<br>        {<br>            if(obsacle.CompareTag(&quot;Obstacle&quot;))<br>            {<br>                //create a reference for the simulaed obstacles and instantiate the new obstacles which has no unneccessary components<br>                var simulatedObstacle = Instantiate(obsacle.gameObject, obsacle.position, obsacle.rotation);<br>                //get the meshRenderer of each obstacle and disable it<br>                if(simulatedObstacle.GetComponent&lt;Renderer&gt;() != null)<br>                {<br>                    simulatedObstacle.GetComponent&lt;Renderer&gt;().enabled = false;<br>                }<br>                //move gameobjects to the new simulated physics scene<br>                SceneManager.MoveGameObjectToScene(simulatedObstacle, _simulatedScene);<br>            }<br>        }<br>    }<br><br>    //reference for the line renderer<br>    [SerializeField] private LineRenderer _line;<br><br>    //create a method to simulate the trajectory<br>    public void SimulatedTrajectory(AirmailPackage airmailPackagePrefab, Vector3 position, Vector3 velocity)<br>    {<br>        //reference for a simulated object(airmailPackage)<br>        var _simulatedObject = Instantiate(airmailPackagePrefab, position, Quaternion.identity);<br>        //disable renderer for simulated object<br>        _simulatedObject.GetComponent&lt;Renderer&gt;().enabled = false;<br>        //move this simulated object to the simulatedPhysics scene<br>        SceneManager.MoveGameObjectToScene(_simulatedObject.gameObject, _simulatedScene);<br>        //apply velocity to the simulated object using Init function<br>        _simulatedObject.Init(velocity);<br>    }<br>}</pre><p>We are going to call this function from launcher class in update, so we need a reference to this class.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Launcher : MonoBehaviour<br>{<br>    //reference to the simulatedPhysics class<br>    [SerializeField] private SimulatedPhysics _simulatedPhysics;<br>    <br>    //create a reference to the package prefab<br>    [SerializeField] private AirmailPackage _airmailPackagePrefab;<br><br>    //reference to the amount of force to apply<br>    [SerializeField] private float _force;<br><br>    [SerializeField] private LabComplete _labComplete;<br><br>    // Update is called once per frame<br>    void Update()<br>    {<br>        //call the simulated trajectory function from simulatedPhysics class<br>        //pass in the prefab to instantiate, the position and the direction multiply by the force<br>        _simulatedPhysics.SimulatedTrajectory(_airmailPackagePrefab, transform.position, transform.forward * _force);<br>        <br>        //get the input from player<br>        if (Input.GetKeyDown(KeyCode.Space))<br>        {<br>            //instantiate the packagePrefab and apply the force<br>            var _spawned = Instantiate(_airmailPackagePrefab, transform.position, transform.rotation);<br>            <br>            //tell package where to instantiate<br>            _spawned.transform.parent = transform.root;<br><br>            //call the init function from the package<br>            _spawned.Init(transform.forward * _force);<br><br>            _labComplete.CheckCriteria();<br>        }<br>    }<br>}</pre><p>So it instantiates it every frame in simulatedPhysicsScene, now we attach simulatedPhysics in inspector, then test it, in game mode we see there a lots of copies are instantiating every frame, we want these copies to be alive for 100 frames for example. But first let’s set up the lineRenderer</p><h4>Scripting the Line Renderer Positions</h4><p>Let’s add a lineRenderer component to our Launcher object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*qO3wKtZwUB1HBA_k76f9UQ.png" /></figure><p>Now we set it’s options, by default it created in global 0,0,0 position</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7NEs1QImykxGGyG77V1QA.png" /></figure><p>we set it’s width, material, color and etc. positions we set it through script which we get from simulated objects.</p><p>Let’s see in Unity API how we can set it’s position</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/LineRenderer.SetPosition.html">LineRenderer.SetPosition</a></p><p>We create it’s reference in SimulatedPhysics class, so let’s set it’s position in this class inside SimulatedTrajectory method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUsbobHi73fDtbM-0HFnxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2uVYJTCI0tg0y-NpNRN5w.png" /></figure><p>Then we set the max iterations and attach lineRenderer component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*iTii7RHRQhq0JbPdXauXAg.png" /></figure><p>Line settings and the material</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*Pw0BL-B7V050NCKjcWzSEA.png" /></figure><p>So everything is ready, let’s test it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsnL6o93d_1DnjCd4TFj6A.png" /></figure><p>Now we see the trajectory, it look little bit jittery and inaccurate. Here we have about 45 FPS, in Launcher class we are calling SimulationTrajectory function in update void, let’s try to put it inside fixedUpdate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NA62GsLwQlBGJTv8Nq2Hyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72W3kSy83kTqM7qUP_pTjQ.png" /></figure><p>Here with this we have very accurate and smooth trajectory, but it gives about 30 FPS. Let’s try to optimize and increase FPS. First make shure that in Line settings there is no any unused setups, almost everything must be turned off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*rc-mnAgvqass7U7OVZ0UnQ.png" /></figure><p>We’ll also decrease maxPhysicsIterations to 20. Now it can’t give us full trajectory. Maybe it will be cutted of on the middle of whole path, we’ll correct it. Let’s look at our SimulationTrajectory function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYfM4MnWATwUMGWxtsidQA.png" /></figure><p>Inside 1st part there is nothing to optimize. But in simulation line if we change deltaTime to fixedDeltaTime, we get much more optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*znPiJtAWmDN4X-k4akb9bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvYUjEQgBAWMLDcJZSMPow.png" /></figure><p>We got here about 100 FPS, but we have half path trajectory. We can set it 100 iterations and go with it, FPS will be fine, but knowing to optimize more by decreasing iterations can be handy in other cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*sIRh2w25yl_BNGYZbLA2Sw.png" /></figure><p>we can increase steps of iterations reaching full path but with more optimized(not much smooth) trajectory, dividing full path to 20 pieces. spacing out the amount of time inbetween simulation points. We reach it adding multiplier to fixedDeltaTime, let’s try for now 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*muNJQsPm1YFAPElN_fxnjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PD1LWYFaWzPWTNO2PfUMBg.png" /></figure><p>We got the same 100 FPS, but also full path trajectory.</p><p>Now Player can adjust the force and angle before launching in gameMode by looking to it’s simulated trajectory.</p><h3>Modifying Gravity</h3><p>In rigidbody component when using Gravity is on Unity uses default gravity which is equal to Vector3 0, -9.81, 0. This is a realistic gravity value. We can check it in project settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*7xKAz1nejs587gaIQoI-WA.png" /></figure><p>If we change it here it allows all objects, for certain objects we can change it though script.</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Physics-gravity.html">Physics.gravity</a></p><p>Let’s create a new Gravity script, setting Physics.Gravity will affect all objects in the scene.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Gravity : MonoBehaviour<br>{<br>    //create a reference to the gravity value<br>    [SerializeField] private float _gravityValue;<br><br>    void Start()// Start is called before the first frame update<br>    {<br>        //apply a different gravity value<br>        Physics.gravity = new Vector3(0f, _gravityValue, 0f);<br>    }<br>}</pre><p>I’ll attach it to my container object with value -1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*HRaZaK-frIUZRqVHtzK_Qw.png" /></figure><p>You can see here some blowed objects are floating over there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fr5W50uIoen2bLZ8cuf0Lg.png" /></figure><p>Now let’s see how to apply different gravity to a single object. We can’t do this using gravity commands, for this we can use forces, for example, ConstantForce</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/ConstantForce.html">ConstantForce</a></p><blockquote>Description</blockquote><blockquote>A force applied constantly.</blockquote><blockquote>This is a small physics utility class used to apply a continous force to an object.</blockquote><blockquote><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Rigidbody.AddForce.html">Rigidbody.AddForce</a> applies a force to the <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Rigidbody.html">Rigidbody</a> only for one frame, thus you have to keep calling the function. ConstantForce on the other hand will apply the force every frame until you change the force or torque to a new value.</blockquote><p>It is a component, we add it in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*9RNF9qsfZtsE1gM7842KWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O225t2MjBjEjhJjMXX0NyA.png" /></figure><p>Here our new gravityValue is -1, if we add force little bit more than 1, I set it to 1.1 container started to rise up. Let’s type a code which will activate this force when by player’s input.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Gravity : MonoBehaviour<br>{<br>    //create a reference to the gravity value<br>    [SerializeField] private float _gravityValue;<br><br>    void Start()// Start is called before the first frame update<br>    {<br>        //apply a different gravity value<br>        //Physics.gravity = new Vector3(0f, _gravityValue, 0f);<br>    }<br>    private void Update()<br>    {<br>        if(Input.GetKeyDown(KeyCode.Space))<br>        {<br>            ApplyLocalGravity();<br>        }<br>    }<br><br>    void ApplyLocalGravity()<br>    {<br>        ConstantForce constantForce = GetComponent&lt;ConstantForce&gt;();<br>        constantForce.force = new Vector3(0f, _gravityValue, 0f);<br>    }<br>}</pre><p>So with this code by pressing space key we set the gravity to one single object that has ConstantForce component and this script not affecting other objects, we actually don’t change the gravity. Tricky but handy.</p><h3>Joints and Articulation Bodies</h3><p>We use joint to connection objects, using joint we connect it by physics engine rather than hierarchy. A joint connects a Rigidbody to another Rigidbody, or to a fixed point in the world, and restricts how the two can move relative to each other. You add a joint as a component to a GameObject that already has a Rigidbody. Unity uses joints for doors, chains, ropes, ragdolls, vehicles, grabbing objects, and similar physics setups. We’ll see 3D joints, there are 5 types of 3D joints: fixed, hinge, spring, character, configurable joints.</p><h4>Fixed joint</h4><p>Let’s explore first fixed joints. Locks two bodies together with no relative movement, for example, welding objects that can later break apart, sticky projectiles. Let’s see how it works. In our lab scene scene we have 2 objects: cube and circle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*QfSIFGNKKpXoJWX5MsmvEw.png" /></figure><p>Let’s fix the cube to circle. If we add to cube a fixed joint component, it also added to it rigidbody compinent automatically. We also have to add rigidbody to circle object, joints work only with rigidbody objects. Then we drag this circle to cube fixed joint connection body</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*RmLn5KHyFOpTeBQrmqv7mw.png" /></figure><p>You can see there are break force/torque are set Infinity by default, it is the max force/torque this fix joint can handle, above this value this fix joint will break.</p><h4>Hinge joint</h4><p>Allows rotation around one axis only, with optional motor, spring, and limits, for example, Doors, levers, wheels, pendulums.</p><p>Let’s add hinge joint between these objects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*RPkrYe9p23Hk6yUrxdCOdw.png" /></figure><p>We have these option by default</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*iomVoxD6wadnt0q0WaWueA.png" /></figure><p>We attach rigidbody of the cylinder type object(Circle_005) to connection Body</p><p>Here next we can set the anchor and angular limits, in edit mode we can see it in viewport. anchor y=0.1 looks fine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynAB0FBoHhfO90-tLsAZbw.png" /></figure><p>Then we enable use limits in motor section and set limits right in viewport by dragging these points</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEj-d9pUXmWcE5ZqC-evCA.png" /></figure><p>This gives us enough movement. we set circle_005 is kinematic for now to testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*dXYufFYdi2zKf8eMy3QuOw.png" /></figure><p>It works, we see it’s hinging. You can test and play with other hinge setting.</p><h4>Spring Joints</h4><p>Pulls two bodies toward a rest distance like an elastic band, for example, Bouncy connections, soft tethers. Earlier we tested for these 2 objects fix joints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*_jfkNWgkfzQOtSOYK2lQ8g.png" /></figure><p>let’s connect them with spring joint and see their behaviour. First, I delete old fixed joint from cube and add spring joint component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ssl5DF_lm23Qt8jae9CrPQ.png" /></figure><p>I already attached connected body. There is two anchors, set these anchors in right place, in our case they will be in the same place, at point 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkiNc4LfPXjwOoeTPTxMdQ.png" /></figure><p>These anchor positions are very important to set them in correct place. Try to put them in other incorrect places and you’ll see unrealistic cringe results. I set the spring value to 100 for start which is more tighter. As greater this value as closer this cube tries to be to the connected body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*bqShm0IrVLP0rvtzKczGFQ.png" /></figure><p>You can play with min/max distance options.</p><h4>Configurable Joints</h4><p>Lets you lock, limit, or free each of the six degrees of freedom (3 linear, 3 angular), with drives, can be used in custom mechanisms, active ragdolls, anything the others can’t do. Let’s try it. In our lab scene there is 2 objects, we set them a piston connection using configurable joints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*J_3LUqP7WSByE6wjVQpjwA.png" /></figure><p>we also add hinge joint to 2nd object to complete this whole chain of objects, then we can check result. After connecting 2nd object to base object with hinge joint we add to 1st object configurable joint, then attach 2nd object to connected body. Then we correct anchors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*rjyGe0m4ODcDYvMq8KazvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*mT_yusESCP9eRlhuCtDpwg.png" /></figure><p>Then we define which axis of movement/rotation to make free/lock/limited. We want only y axis movement and no rotation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*9MWPLfYV5N1TIsASNyqyLA.png" /></figure><p>While testing you can play with spring, mass scale and limit settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*E1EwnS4MQRVFA9U1LwNrag.png" /></figure><h4>Articulation Bodies</h4><p>An <strong>ArticulationBody</strong> is a physics component built for chains and trees of connected bodies, such as robotic arms, legged robots, cranes, and vehicles with suspension. We use it for already prepared hierarchy of objects.</p><p>How it’s structured. An articulation is built from the <strong>GameObject hierarchy</strong>. It is not built from a “connected body” reference like regular joints.</p><pre>RobotBase        (ArticulationBody - root, Immovable = true)<br> └─ Shoulder     (ArticulationBody - Revolute)<br>     └─ Elbow    (ArticulationBody - Revolute)<br>         └─ Wrist    (ArticulationBody - Spherical)<br>             └─ Gripper  (ArticulationBody - Prismatic)</pre><p>The topmost ArticulationBody is the <strong>root</strong>. Each child’s joint connects it to its parent. If you tick <strong>Immovable</strong> on the root, it is anchored to the world, which works for a bolted-down robot arm. If you leave it unticked, the whole structure moves freely, which works for a walking robot or a car.</p><p>Let’s use it for this robot arm in lab scene</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZqQq2zzfghW3yLgnnVFfw.png" /></figure><p>We’ll start with base by adding to it articulation body component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*4nQv9vVwkbb_Tk5JVIpfbg.png" /></figure><p>We set it immovable, then we add articulation body to the next joint_1 object, this options does it have when the object is not the root</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*er1XSh6Lq2X53zhf6HzRaA.png" /></figure><p>in most cases tensor and Center of Mass better to set to automatic. First we do here is to set articulation joint type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*8HUxHOhDhxSDv0s9cF05aA.png" /></figure><p>fixed is for non-movable objects, prismatic is for one axis movable(sliding) like piston connections, revolute is for one axis rotation, pherical is for 3 axis rotation like human shoulder joint. We set here revolute, then we can set the motion to free or limited</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*PmVyT-HukIJo-GWbz7qTkg.png" /></figure><p>Next thing to set is it’s drive type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*Cq6v6q2UedSlUIoMsjpqbA.png" /></figure><blockquote>The four types</blockquote><blockquote><strong>Force</strong> is the default. The output is applied directly as a force (prismatic joints) or torque (revolute and spherical joints), so the drive’s behavior depends on the mass and inertia of the links it moves. A stiffness that feels snappy on a light gripper will feel sluggish on a heavy arm segment. You tune stiffness and damping per joint, so this type gives the most physically realistic behavior and the most work.</blockquote><blockquote><strong>Acceleration</strong> applies the output as an acceleration rather than a force. Unity scales it by the effective inertia of the joint, so the same stiffness and damping give the same response regardless of how heavy the links are. This makes tuning much easier: you can reuse one set of values across joints of different sizes, or change link masses without retuning. forceLimit still caps the actual force applied.</blockquote><blockquote><strong>Target</strong> asks you only for target. Unity computes stiffness and damping internally so the joint tries to reach the target within a single simulation step. The Inspector hides the stiffness and damping fields for this type. It behaves like a very stiff, well-damped servo, which suits kinematic-style control where you want a joint to go exactly where you say. Set a sensible forceLimit, or it can produce violent motion and fight collisions hard.</blockquote><blockquote><strong>Velocity</strong> asks you only for targetVelocity. Unity computes damping so the joint tries to reach that speed within one step, and position is ignored. Use it for wheels, conveyor rollers, spinning tools, or any joint you control by speed rather than angle.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*iFmrKX0IT47yvtLUdDpevA.png" /></figure><p>You can set them as you want and test in game mode.</p><p>Next joint I’ll make as revolute limited, you can set it’s limits in edit mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*XBES7KFADiYKzGteaLZHCQ.png" /></figure><p>So I set other joints, most of them are revolute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTOIK3Z2jwsLsj4kXDwymQ.png" /></figure><p>I set this one as prismatic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*FO3GOzC-vkB6JgPBLOoB0A.png" /></figure><p>with these limits</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*Wr0kdua6CdFqnD2HoZpXvw.png" /></figure><h3>Ragdoll Physics</h3><p>A ragdoll is a character whose bones are driven by physics instead of animation. Each major bone gets a <strong>Rigidbody</strong>, a <strong>Collider</strong>, and a <strong>joint</strong> connecting it to its parent bone. Ragdolls are most often used for death animations, knockbacks, and explosions. With extra work they can also power “active ragdoll” characters that balance and move using physics.</p><blockquote>Creating one with the Ragdoll Wizard</blockquote><blockquote>Unity has a built-in wizard that does most of the setup:Import a rigged humanoid character and place it in the scene.Open <strong>GameObject → 3D Object → Ragdoll… </strong>Drag the matching bones from the hierarchy into each slot: Pelvis, Left/Right Hips, Knees, Feet, Arms, Elbows, Middle Spine, and Head. Set <strong>Total Mass</strong> (around 70 for an adult human). The wizard distributes it across the bones. Click <strong>Create</strong>.</blockquote><blockquote>The wizard adds a Rigidbody, a Capsule, Box, or Sphere Collider, and a <strong>Character Joint</strong> to each bone. Press Play and the character collapses. After running it, check the colliders in the Scene view and resize any that don’t fit the mesh well, especially the spine and head.</blockquote><p>Here in our lab scene there is a character rigged model with prepared mesh and bone hierarchy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWMwc_wkF6nAMZRoUUMdew.png" /></figure><p>select the prefab object FireMan_Rigged then create Ragdoll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Ye6wfTKXNKvcVGdtFGuOlw.png" /></figure><p>It opens a ragdoll wizard window where you have to attach some main joints(bone objects)from scene window into required spaces of this window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*SfOxMIKYBoWP6xaAnMCdWQ.png" /></figure><p>Attached everything as needed Total mass and strength kept by default</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*kz9R9DyZu9tBlNVLE_scxQ.png" /></figure><p>After create you see this shape here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGTRvHQnidKS5_b3RDzfdw.png" /></figure><p>You can see that default collider sizes doesn’t fit the actual mesh parts at all. We have to correct them manually. Let’s start with head, select head and in inspector find the collider component and turn on edit mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGDkiqRubuUgs269RCI27Q.png" /></figure><p>Other parts also, now it’s better</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*sIO6KeQB_GM-lkx__UH-2w.png" /></figure><p>We can test it and see how it falls</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*wSPj-8jfNy-Nw2owEYenXQ.png" /></figure><h4>Adding New Ragdoll Joints</h4><p>Let’s say we want to add some parts like foot, separate hand parts etc. This Ragdoll wizard automatically adds required Rigidbody, Collider and Character joint components with proper settings, we can modify these existing components, change their parameters or add these components to specific rig parts and manually correct their options. Let’s start with foot.</p><p>First I set the collider as child empty object, because rig joint object has rotation which is not suitable with collider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50gue3O7x7OItZ_9LMYusQ.png" /></figure><p>Then I added to main rig foot object rigidbody and character joint components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*x16xZunSNu9guEFfVZFSIg.png" /></figure><p>Attached connected body. Edited angular limits</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MQAAJ5INrnr-46DQyb5Ww.png" /></figure><p>Do the same with left foot, then we set up hands. But before I have to add just colliders to gas cylinders at back inside spine2 joint object(because it is the closest joint in hierarchy)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-x1-0M1Un-fdPhvbZR7aEQ.png" /></figure><p>Let’s set up hands. First we find the wrist(hand) joint placement, it is here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVc0OsXErjEyDRADd68-fw.png" /></figure><p>so forearm collider must end here, and next collider must start at this place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*sZ6LDq_EjK_ECT5_TkvHgw.png" /></figure><p>If you add a character joint Unity automatically adds also rigidbody if it doesn’t exist in this object. Then we correct angular limits</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*ZVvNCWak4TSgowrDLQN6LQ.png" /></figure><p>Z direction which is blue color is for twisting limit. Set also second hand. Before testing tag the prefab object and one of foot rig objects as labItem to initiate labComplete. Tested, looks good!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*4JQ_GMdYuJn2qQj2mJCX7Q.png" /></figure><p>There are also lot’s of parameters of all these physics components and there could be different unique situations to solve, in here I showed the main options.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=686c9d9f577a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GME 302: Physics In Unity. Part-1]]></title>
            <link>https://medium.com/@yanvar103/gme-302-physics-in-unity-part-1-e062abd37acb?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/e062abd37acb</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 06:58:23 GMT</pubDate>
            <atom:updated>2026-09-26T06:58:23.189Z</atom:updated>
            <content:encoded><![CDATA[<p>For this I’ll use Unity version 2022.3.76f1 which is latest 2022 version.</p><p>I couldn’t create new priject on this version because of it has Extended LTS, so I’ll try with 2022.3.55f1.</p><h3>Rigidbody Basics</h3><p>To simulate physics in Unity we add Physics(not 2D) category components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*7T0LL7W2PRIwFLF2NEV_uw.png" /></figure><p>Physics in Unity can solve lots of different physical interactions and simulations, but they might cost expensive on resource side, we will talk about optimization later. All those calculations run in the background. One of them is rigid body, if we add it has default options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*r4R30OL7dgyDzCdTekagjA.png" /></figure><p>If we click Play we see it goes through the floor, to interact with other gameObjects we also need to add collider. For this object we add box collider. It automaticly gets the shape from mesh filter. These two components are important while we simulate physic object interactions.</p><h3>Colliders</h3><h4>Working with Primitive Colliders</h4><p>We 3 primitive colliders: Box, Capsule, Sphere. In projects we have use primitive colliders as much as possible, because they help with optimization. When we add a collider to the object, first we see it’s shape, if it approximately close to one of these primitive shapes, if yes we use them.</p><p>For example we can give this object box collider using model bounding box shape</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*I_rmoyckBKKdkxBJBCzhFg.png" /></figure><p>But if we want to shoot through gap of these cylinders we can use group of primitive collider which allows us to do it, if we see the shape of this, it has box and cylinder shape objects. Let’s build this thape from primitive colliders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*mvjFotk6NMKUq109kq4-8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*pwOhKyDiwn61hXoDzDv1ig.png" /></figure><p>It costs more expensive, but in some cases when we need this much accurate result we have to go with this way. Let’s see one more example, we have a barrel with approximately cylinder shape, let’s try for it capsule collider. in this case if we push it little bit it falls because of its round bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*Vsp-hWlTk4PncVuGj3sKwg.png" /></figure><p>To avoid this we can make it’s bottom as box collider like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*h_rcHHr3pZVUD5b2YGLgew.png" /></figure><p>Now it is more stable on the ground. Here are some another examples with primitive colliders combinings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*h9pPznpjHY4jq45fQOawbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*qyV83l-heDP2Ik52MV7bAA.png" /></figure><p>Editing colliders shape you can using this button and you can switch to orthographic view for more comfortable editing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*aW6OSLWqI1NQLXtWgfIA2Q.png" /></figure><p>Let’s do the final example more accurate by rotatin colliders using empty child gameObjects. It is a tricky way, but effective. Colliders by itself we can’t rotate, they have no this function. Under the object we add child empty objects and attach to them colliders, then we rotate the child object and with it rotates also a collider attached to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIajIpunubp0JKrlhI-kIg.png" /></figure><p>So we can get now much more accurate collider shape using compound primitive colliders with empty child objects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*hDmCvvVRWFImT-CYj84sjg.png" /></figure><p>While dublicating and rotating other legs better switch to Global mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*l_jyy_k_fMc3HRgteQnCyg.png" /></figure><p>One more usefull hint: if you hold ALT key while draging the size of collider in edit mode it will keep the center at the same place which is very usefull when you work with symmetric objects.</p><h4>Terrain Colliders</h4><p>We can create terrain as any 3d gameObject</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*0CiomANySmfFV72RUk4udw.png" /></figure><p>By default it is very large, you can scale it up to fit, for example, to our lab size. But be carefull to scale gameObjects wich are going to be simulated, because simulating object which has scale transform different from 1 can produce unpredictable results. So that’s we I recommend you to set it’s width and length or other size settings inside Terrain settings instead of scaling it’s transform node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*QnIVYwnrXAHERXlqxldyWA.png" /></figure><p>It has lot’s of other parametres, also you can give it a material, more detail information about terrains maybe I’ll do another article. But now for physics important thing here is it’s terrain collider component added by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*FmjYZqDq8DJ2F2ZwVkZUYg.png" /></figure><p>Notice that it has Tarrain Data “New Terrain”. It automatically creates inside assets folder when you create terrain object in scene, let’s rename it as example terrain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*RGEqWfq3AFf28U2cNUxRSQ.png" /></figure><p>Also it has Material inside Terrain Collider, it is a material which defines it’s physical parameters such as bounciness, frictions etc. We’ll talk about materials later.</p><p>There is also Enable Tree Colliders, if you don’t have any trees or something like this placed in terrain, it’s better to tick off it, because in play mode, if this enabled unity always do unnecessary checking if there any trees on terrain.</p><h4>Mesh Colliders</h4><p>Let’s add a mesh collider to this kind of barrel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*tVbFqhYcTmI3TAIzCnJmjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*bmqIVKElKTytQqq0iN8gOg.png" /></figure><p>If you enable Convex you see the collider almost corresponding to the polygonal mesh, with Convex on it cuts off holes and concave parts on an object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*1lIL293R0i2q1Jn1iHQPeA.png" /></figure><p>If we turn it of it still has a collider exactly corresponding to the polygonal mesh which is the most accurate, but it is unvisible in scene view. If run play mode we see and error</p><p>“Non-convex MeshCollider with non-kinematic Rigidbody is no longer supported since Unity 5. If you want to use a non-convex mesh either make the Rigidbody kinematic or remove the Rigidbody component”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*atRNfct3I_gPmf2CcpIpbA.png" /></figure><p>So if we enable Kinematic in rigidbody, which means The physics engine for this object <strong>ignores</strong> gravity and forces entirely, It <strong>won’t</strong> be pushed around by collisions with other physics objects — it acts like an unstoppable, immovable force, but It <strong>still generates collision/trigger events. It is stationary and can be moved only by </strong>via transform.position, transform.Translate(), or (better) rigidbody.MovePosition() / rigidbody.MoveRotation().</p><p>We can use mesh collider for concave shaped objects with unchecked convex mode as an objects that will collide as static. For example let’s create little sphere with rigidbody above this barrel and play it. It will bounce on it few times roll on it and even pass through the side hole. With this way we can use it’s collider as much accurate as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*e82E9nq9LyZVJOr0wfbhAA.png" /></figure><p>Here it was used for physics simulation for another rigidbody object.</p><p>With using mesh collider you will double the amount of vertices for this object. If it has about 300 vertices, with mesh collider it will have about 600 that has to be taken into a count. To optimize this, as mesh reference better use more optimized mesh version with less vertices, you can create it in 3d model editors such as 3dsmax, blender, maya etc. In real projects for this case there is always prepared this type of optimized mesh reference. You only have to attach it here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*8bcy2NqUNbIkRkmFST_66A.png" /></figure><p>But in our case we want is kinematic to be checked of for this object and we use convex mode on. In this mode unity creates mesh collider using original mesh reference with some Cooking options, by default everything is here are enabled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*BwwG9EL9XYS9DYQY5A6W0Q.png" /></figure><p>If we turn on wireframe you can compare the meshes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*riJQhYuxMsqzalGBG43hRA.png" /></figure><p>and see that with this cooking options collider mesh is more optimized. But it is much more accurate compared to compound primitive colliders.</p><h4>Wheel Colliders</h4><p>Before adding wheel collider to Vehicle object we must prepare the right structure of Vehicle object. It must be a Vehicle empty GameObject on the top as a parent for all other parts. It contains only rigidbody component. Also we create under it another empty GameObject only for physics. In our case it will be WheelsColliders object which will contain all wheel colliders for all 4 wheels. Under WheelsColliders we add 4 empty objects with wheel collider components for each wheel. Their position must match with the position of the corresponding mesh wheel. For this we just copy and paste position values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*y-UaJMJJJ6fYXDaj9uDRrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*9b_veHAe_A9YcVF7eJWQbg.png" /></figure><p>And you see their pivot centers will match but not the shape, it is ok, don’t try match their shapes by modifiing position and radius, you don’t need to change it’s position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*sJPaBOdgJNOzI9O2fBTsQg.png" /></figure><p>Here is a Wheel Collider component options(by default) and here you can see suspention radius. It is relative to this shape in viewport</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*L9eXucxEtiKoYefVVTlUmg.png" /></figure><p>set it to 0, the match the radius of wheel collider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0plSpDzEMdv_4mvfJYfww.png" /></figure><blockquote><strong>Suspension Distance</strong> defines the maximum vertical travel of the wheel — how far the wheel can move up and down from its resting position due to the suspension.</blockquote><blockquote>It’s measured in meters, along the local Y-axis of the wheel.</blockquote><blockquote>The wheel’s suspension starts at the WheelCollider’s local position and can compress or extend up to this distance downward, seeking contact with the ground.</blockquote><blockquote>If the distance is too small, the wheel might not reach the ground (especially on bumpy terrain), causing the vehicle to feel like it’s “floating” or the wheels not touching properly.</blockquote><blockquote>If it’s too large, the suspension can feel too soft/bouncy, and the wheel may extend too far down, causing odd visual or physical behavior.</blockquote><p>Now, after we set up the radius let’s set the suspension distance to close to default value 0.25.</p><p>1st wheel collider is ready, if other wheels are identical you can dublicate this wheel collider and match their positions with other corresponding mesh wheels. If not you have to set also their radius. In our case they are identical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6K6ZATEBv0Ln-wa7HO6tA.png" /></figure><p>If you test it, you see when it touches the ground it bounces very high. It’s because in rigidbody component of Rover(parent object) has mass 1(kg). very small relative to suspension spring force. In real life vehicles have much more mass for this rover we can set for example 400kg. So it is not crazy bouncing now, You can also notice that mesh wheels aren’t turning, but wheel colliders turning. We have to set them.</p><p>On note before this: When we added rigidbody to Rover, it has by default Automatic Center of Mass is checked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*hpLeKDKlX2wMAtd9cZux5w.png" /></figure><p>Let’s uncheck it and set it manually</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*sArPa6VG08qLRxk0X9_K_w.png" /></figure><p>So, where is actually center of mass is located we can see by using Physics debugger window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*NgdbhKnLqMP43ULXJ2R5rA.png" /></figure><p>Then check collision geometry and use Draw Gizmos for: Center Of Mass</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zdckE8NDs8qDza3TgIyDw.png" /></figure><p>If it is too low like this(in here is has 0,0,0 values), it causes different bugs like sticking in place when suspension distance is high enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*2wSjv_8N12InGZYba7kEvw.png" /></figure><p>If we set it to auto Center of mass will have these values, actually it’s fine to set them auto</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZ2GLCqOcb50a32lMpgRlA.png" /></figure><p>In my case it better works with Center of Mass with 0,0,0 values, you can test with it on your own. Our structure will be like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*r97KGebQkrXBZJFrvuChUQ.png" /></figure><p>1-st part is for physics, 2nd is for visuals(mesh) and a parent Rover that has a rigidbody component.</p><p>Now time to rotate the wheels via script.</p><h4>Scripting the Wheel Visuals</h4><p>In Unity scripting API 2022.3 let’s search for WheelCollider and search for something like position and rotation, here is what we are looking for</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5BnBYVACTl1NErKbBnaHg.png" /></figure><blockquote>public void <strong>GetWorldPose</strong>(out <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Vector3.html">Vector3</a> <strong>pos</strong>, out <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Quaternion.html">Quaternion</a> <strong>quat</strong>);</blockquote><blockquote>Description</blockquote><blockquote>Gets the world space pose of the wheel accounting for ground contact, suspension limits, steer angle, and rotation angle (angles in degrees).</blockquote><p>using this command we get collider world position and rotation and set them into mesh. For this we use void fixedUpdate(), in general we always use fixedUpdate when we are working with physics. Because,</p><blockquote><strong>Update() runs once per rendered frame.</strong> The frame rate varies: 144 FPS on a fast PC, 30 FPS on a weak phone, and it changes from moment to moment when things get heavy. So the time between two Update() calls is never the same.</blockquote><blockquote><strong>FixedUpdate() runs on a fixed timestep</strong>, 0.02 seconds (50 times per second) by default, set in <em>Edit → Project Settings → Time → Fixed Timestep</em>. The physics engine (PhysX) simulates in these same fixed steps: right after each FixedUpdate(), Unity advances the physics world by exactly that amount of time.</blockquote><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Wheels : MonoBehaviour<br>{<br>    //get a reference to the wheelCollider<br>    //get a reference to the wheel mesh<br>    //get world transform values of wheelCollider using public void GetWorldPose<br>    //set the transform values of the wheel mesh<br>    [SerializeField] private WheelCollider _wheelCollider;<br>    [SerializeField] private Transform _wheelMesh;<br><br>    private void FixedUpdate()<br>    {<br>        Vector3 _wheelPosition;<br>        Quaternion _wheelRotation;<br><br>        _wheelCollider.GetWorldPose(out _wheelPosition, out _wheelRotation);<br>        _wheelMesh.transform.position = _wheelPosition;<br>        _wheelMesh.transform.rotation = _wheelRotation;<br>    }<br>}</pre><p>This is for one wheel, to test it attach it to Rover object and define collider and mesh in inspector. I tested it works, next is to modify this script to be common for all wheels, we can use arrays and for loop.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Wheels : MonoBehaviour<br>{<br>    [SerializeField] private WheelCollider[] _wheelCollider;<br>    [SerializeField] private Transform[] _wheelMesh;<br><br>    private void FixedUpdate()<br>    {<br>        for (int i = 0; i &lt; _wheelCollider.Length; i++)<br>        {<br>            Vector3 _wheelPosition;<br>            Quaternion _wheelRotation;<br><br>            _wheelCollider[i].GetWorldPose(out _wheelPosition, out _wheelRotation);<br>            _wheelMesh[i].transform.position = _wheelPosition;<br>            _wheelMesh[i].transform.rotation = _wheelRotation;<br>        }        <br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*Awl_b7Q7xLKCiAMCApevwg.png" /></figure><p>I worked on it and made it better more optimized and better structured</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Wheels : MonoBehaviour<br>{<br>    <br>    [System.Serializable]<br>    private struct Wheel<br>    {<br>        public WheelCollider collider;<br>        public Transform mesh;<br>    }<br><br>    [SerializeField] private Wheel[] _wheels;<br><br>    private void Update()<br>    {<br>        for (int i = 0; i &lt; _wheels.Length; i++)<br>        {<br>            _wheels[i].collider.GetWorldPose(out Vector3 position, out Quaternion rotation);<br>            _wheels[i].mesh.SetPositionAndRotation(position, rotation);<br>        }        <br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*qlH3ASEKdwCdRAZKG0Na7g.png" /></figure><p>In here I used Update instead of fixedUpdate, because:</p><blockquote>This is the main issue. Copying the pose to the mesh is <strong>visual work, not physics</strong>. You’re only reading from the WheelCollider, not applying forces, so it doesn’t need to run in FixedUpdate(). You can keep motorTorque, brakeTorque, and steerAngle in FixedUpdate(), because those are physics.</blockquote><p>In lessom Teacher did it using list WheelCollider and wheel mesh as a child under it(restructured hierarchy), then used foreach for this list.</p><blockquote>List + foreach vs array + for</blockquote><blockquote>These are basically equivalent here. A List can change size at runtime, which you don&#39;t need for wheels, so an array is fine. foreach is a bit cleaner to read, while for gives you an index, which is handy if you need to know which wheel you&#39;re on (e.g. &quot;wheels 0 and 1 steer&quot;). There&#39;s no meaningful performance difference for 4 items.</blockquote><p>Here is a child approach:</p><pre>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Wheels : MonoBehaviour<br>{<br>    [SerializeField] private List&lt;WheelCollider&gt; _wheels;<br><br>    private void Update()<br>    {<br>        foreach (WheelCollider wheel in _wheels)<br>        {<br>            wheel.GetWorldPose(out Vector3 position, out Quaternion rotation);<br>            wheel.transform.GetChild(0).SetPositionAndRotation(position, rotation);<br>        }<br>    }<br>}</pre><p>You can chose any of these two approaches, I’ll go with 1st one, because I’d like to keep existing structure hierarchy without any changes.</p><h3>Triggers</h3><p>Triggers can trigger some event when one object intersects with another one. In scene we create an empty object and call it trigger. We add to it a collider component, in most cases we will add box collider, in doorways for example. Inside this collider we have to check is trigger option. When this option is checked other objects can intersect this collider, and when we attach to this trigger a script which has OnTriggerEnter function it can fire some events through this script. There also has OnTriggerExit and OntriggerStay functions. Let’s create a Trigger script and attach it to our Trigger object. Let’s do something using OntriggerEnter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwvqptKvX_wLbO3sfNzBeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*KFK5oZ98jcvKIek9JMJa-Q.png" /></figure><p>Here you see 2 barrels color turned to red, 3rd one which didn’t collide didn’t change the color. We also can attach this script to barrels, but with this way we must use Game object instead of using other:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zycldd_mJdcjsVbRMiG6EA.png" /></figure><p>Both will give the same resoult. Here is a task: Use existing trigger of restraint for switching Barrales emissive color to bright green when then fall into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbEP8I2kN2QUrAINgr879w.png" /></figure><p>In script we use SetColor that requires string name of emissive channel color, also we can multiple it to float number bigger than 1f to increase it’s intensity</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Trigger : MonoBehaviour<br>{<br>    private void OnTriggerEnter(Collider other)<br>    {<br>        other.gameObject.GetComponent&lt;Renderer&gt;().material.SetColor(&quot;_EmissionColor&quot;, Color.green * 5f);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*DGxcjevBKfEd5vRJiUAu8Q.png" /></figure><h3>Physics Materials</h3><p>In addition to the visual shader materials Objects also has a physic materials. We create them in project window as simple material</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*L6VGi85MyIzcXBWmKAGdgA.png" /></figure><p>Let’s create two different materials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*ZPwCaqJ3MFj8WJVxqbwELg.png" /></figure><p>By default it has these options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*7GMDn3EnKUK8GgTmg97eGQ.png" /></figure><p>Dynamic friction for moving objects, in real life static friction always is little bit higher than dynamic. For smooth and rough materials we can set them like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*ziizoXEldoOymm4LMf_gLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*4pyVwdWM1rZZO9cGErKY7g.png" /></figure><p>Bounciness is an ability to bounce, it is between 0–1, if 1 it will bounce infinitively. In our case we don’t need bounciness. Combine options are to defining overall friction or bounciness with two touching surfaces with 2 different materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*noN-EuYURUINCAkXOjH-kQ.png" /></figure><p>Avarage is suitable in our case.</p><p>Now we attach those materials to our objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5q-X0LRbcjWsVm75M87rw.png" /></figure><h3>Applying Forces</h3><blockquote>In Unity, a Rigidbody component provides a physics-based way to control the movement and position of a GameObject. Instead of the <a href="https://docs.unity3d.com/2022.3/Documentation/Manual/class-Transform.html">Transform</a> properties, you can use simulated physics forces and torque to move the GameObject, and let the <strong>physics engine</strong></blockquote><blockquote>In most cases, if a GameObject has a Rigidbody, you should use the Rigidbody properties to move the GameObject, instead of the Transform properties. The Rigidbody properties apply forces and torque from the physics system, which change the GameObject’s Transform; if you then change the Transform directly, Unity cannot correctly calculate the physics simulation, and you might see unwanted behavior. This is particularly true of rigid bodies with Joints.</blockquote><blockquote>Unity handles physics-based movement globally, not locally. When a GameObject with a Rigidbody moves via physics-based movement, it moves independently of any parent or child GameObject. A child GameObject that has a Rigidbody still uses its parent GameObject to define its local position for initialization, but Unity calculates its physics-based movement in global space.</blockquote><blockquote>To control a Rigidbody via script, the primary methods are <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Rigidbody.AddForce.html">AddForce</a> (to add forces to a GameObject) and <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Rigidbody.AddTorque.html">AddTorque</a> (to apply torque to a GameObject).</blockquote><p>Here you can read lot’s of usefull information about forces and forceModes</p><ul><li><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Rigidbody.AddForce.html">Rigidbody.AddForce</a></li><li><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/ForceMode.html">ForceMode</a></li></ul><blockquote>Force is applied continuously along the direction of the force vector. Specifying the <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/ForceMode.html">ForceMode</a> mode allows the type of force to be changed to an Acceleration, Impulse or Velocity Change.</blockquote><blockquote>The AddForce function impacts how your GameObject moves by allowing you to define your own force vector, as well as choosing how to apply this force to the GameObject (this GameObject must have a Rigidbody component attached).</blockquote><blockquote>ForceMode allows you to choose from four different ways to affect the GameObject using this Force: Acceleration, Force, Impulse, and VelocityChange.</blockquote><p>Let’s see them in practice. We’ll create a new script and name it ApplyForces.</p><p>We define a reference for rigidbody component, then we’ll add force Vector3 direction by Z axis(towards), and here we can add one of these force modes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwFqIxdtpipu12ZEaY2NbA.png" /></figure><p>Here acceleration and VelocityChange completely ignores objects’s mass. For example we can use them in rocket moving cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*Ta-2zxQ5lwIc5T3bgBnI0A.png" /></figure><p>Let’s try Impulse. With this impulse I want to push this cube towards to the portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*cfOijQPW4t7Ro-E1y_wFSA.png" /></figure><p>If I tested it pushed it in opposite way, because in viewport it was in local mode. Physics work with world coordinates. So if I switch to Global I can see the script is working ok</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*aN0q9JqChdJeAFrPZneGWw.png" /></figure><p>I just need to set the Vector3 to opposite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*1aU0BtDu-uVRSb9oSh_4Hg.png" /></figure><p>Or use relativeForce</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*S0ISJb6P0JwVfxG6bdbOrA.png" /></figure><p>We used it in start update, let’s use it inside fixedUpdate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*KtH8zbCOCzgfhaXbATRxHg.png" /></figure><p>I rotated start position little bit, in this situation If I add force in start I’ll get resoult 1, by using it in fixedUpdate I get resoult 2. It will hit the glass as it has collider, it will stop the cube. But there is one note when we are talking about very fast moving objects, it is about Collision Detection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*db6LrgUFlnXVe9lSHfZcJQ.png" /></figure><p>by default it set as discrete by optimization puspose. If object moves very fast this may not detect collision properly, for this case we can use Continuous Dynamic. In this option collision detection is more frequently and it doesn’t miss the collision.</p><h4>Applying Torque</h4><p>Here is some information about Rigidbody.addTorque</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Rigidbody.AddTorque.html">Rigidbody.AddTorque</a></p><p>Adding torque is almost the same as adding force. Let’s do one task, lets add a force and torque to the cube to make it move with this direction with spinning(using torque) into the portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*vTxNfVXLkWivtI0nBtG-Iw.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class ApplyForces : MonoBehaviour<br>{<br>    //reference to the rigidboy<br>    private Rigidbody _rb;<br>    private float _forceValue = 10f;<br>    private float _torqueValue = 1f;<br><br>    void Start()// Start is called before the first frame update<br>    {<br>        //Get the rigidbody component<br>        _rb = GetComponent&lt;Rigidbody&gt;();<br>        //AddForce to Rigidbody(with different ForceModes)<br>        _rb.AddRelativeForce(0, _forceValue * 0.7f, _forceValue * 0.7f, ForceMode.Impulse);<br>    }<br><br>    // Update is called once per frame<br>    void FixedUpdate()<br>    {<br>        //AddForce to Rigidbody(with different ForceModes)<br>        _rb.AddRelativeTorque(_torqueValue, 0, 0, ForceMode.Impulse);<br>    }<br>}</pre><p>This is one of possible ways to reach this resoult. Here I multiplied force to 0.7f as cos45 degrees.</p><p>With torque we can add some spinning effects, for example, when barrel is blowing with swirling.</p><h3>Detecting Collisions</h3><p>Detecting collisions is more about OnCollisionEvents when one rigidbody object collides with another collider object.</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/Manual/collider-interactions-oncollision.html">OnCollision events</a></p><blockquote>Collision events occur when two non-trigger <strong>colliders</strong><br> make contact.</blockquote><blockquote>Example uses for <strong>collision</strong><br> events include:</blockquote><blockquote>When a projectile hits a target, destroy both the projectile and the enemy.</blockquote><blockquote>When a player character touches a door, trigger an animation to open the door.</blockquote><blockquote>When a player character touches a power-up, increase the player’s size.</blockquote><blockquote>Working with collision events primarily involves the following API functions:</blockquote><blockquote><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collider.OnCollisionEnter.html">Collider.OnCollisionEnter</a>: Unity calls this function on each collider when two colliders first make contact.</blockquote><blockquote><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collider.OnCollisionStay.html">Collider.OnCollisionStay</a>: Unity calls this function on each collider once per physics update while two colliders are in contact.</blockquote><blockquote><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collider.OnCollisionExit.html">Collider.OnCollisionExit</a>: Unity calls this function on each collider when two colliders cease contact.</blockquote><blockquote>For collision events, at least one of the objects involved must have a dynamic physics body (that is, a Rigidbody or ArticulationBody that has <strong>Is Kinematic</strong> disabled). If both <strong>GameObjects</strong> in a collision are kinematic physics bodies, the collision does not call OnCollision functions.</blockquote><p>Let’s see how to use OnCollisionEnter, here you also can see nice examples</p><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collider.OnCollisionEnter.html">Collider.OnCollisionEnter(Collision)</a></p><blockquote>OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.</blockquote><blockquote>In contrast to <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collider.OnTriggerEnter.html">OnTriggerEnter</a>, <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collider.OnCollisionEnter.html">OnCollisionEnter</a> is passed the <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collision.html">Collision</a> class and not a Collider. The <a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Collision.html">Collision</a> class contains information, for example, about contact points and impact velocity. Notes: Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached. Collision events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.</blockquote><p>Let’s create a new script DetectCollisions, we attach it to our Rigidbody object in our lab scene</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGjdX0BPdAJQRmyz1xkZ7g.png" /></figure><p>other barrels on the floor are only colliders, they tagged as Hazard, and the rigidbody is tagged as LabItem. We are going to detect these objects using these tags. So here is a very simple example how to detect collision objects using OnCollisionEnter with tags, notice that here I used CompareTag instead of tag, tag is a legacy method, CompareTag is more optimized new way.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class DetectCollisions : MonoBehaviour<br>{<br>    private void OnCollisionEnter(Collision collision)<br>    {<br>        //Detect collisions with objects tagged as Hazard<br>        if(collision.gameObject.CompareTag(&quot;Hazard&quot;))<br>        {<br>            Debug.Log(&quot;We collided with Hazard object&quot;);<br>        }<br>    }<br>}</pre><h4>AddExplosiveForce</h4><p><a href="https://docs.unity3d.com/2022.3/Documentation/ScriptReference/Rigidbody.AddExplosionForce.html">Rigidbody.AddExplosionForce</a></p><blockquote>Applies a force to a rigidbody that simulates explosion effects.</blockquote><blockquote>The explosion is modelled as a sphere with a certain centre position and radius in world space; normally, anything outside the sphere is not affected by the explosion and the force decreases in proportion to distance from the centre. However, if a value of zero is passed for the radius then the full force will be applied regardless of how far the centre is from the rigidbody.</blockquote><blockquote>This function applies a force to the object at the point on the surface of the rigidbody that is closest to explosionPosition. The force acts along the direction from explosionPosition to the surface point on the rigidbody. If explosionPosition is inside the rigidbody, or the rigidbody has no active colliders, then the center of mass is used instead of the closest point on the surface.</blockquote><blockquote>The magnitude of the force depends on the distance between explosionPosition and the point where the force was applied. As the distance between explosionPosition and the force point increases, the actual applied force decreases.</blockquote><blockquote>The vertical direction of the force can be modified using upwardsModifier. If this parameter is greater than zero, the force is applied at the point on the surface of the Rigidbody that is closest to explosionPosition but shifted along the y-axis by negative upwardsModifier. Using this parameter, you can make the explosion appear to throw objects up into the air, which can give a more dramatic effect rather than a simple outward force. Force can be applied only to an active rigidbody. If a GameObject is inactive, AddExplosionForce has no effect.</blockquote><p>Let’s use it in our lab scene. We want our capsule fall between hazard barrels on the floor and explode pushing these barrels away by explosion force</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*fzoyAgdqzPCA2oa1V6-jIg.png" /></figure><p>First we must add to all of these barrels rigidbody component. I see they already has rigidbody. Let’s type the script which we’ll attach to capsule(falling barrel).</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class DetectCollisions : MonoBehaviour<br>{<br>    [SerializeField] private float _radius = 5f;<br>    [SerializeField] private float _power = 10f;<br>    <br>    private void OnCollisionEnter(Collision collision)<br>    {<br>        //Detect collisions with objects tagged as Hazard<br>        if(collision.gameObject.CompareTag(&quot;Hazard&quot;))<br>        {<br>            Debug.Log(&quot;We collided with Hazard object&quot;);<br>            <br>            Vector3 explosionPos = transform.position;<br>            Collider[] colliders = Physics.OverlapSphere(explosionPos, _radius);<br>                        <br>            foreach (Collider collider in colliders)<br>            {<br>                Rigidbody rb = collider.GetComponent&lt;Rigidbody&gt;();<br>                if (rb != null)<br>                    rb.AddExplosionForce(_power, explosionPos, _radius, 3.0f, ForceMode.Impulse);<br>            }<br>        }<br>    }<br>}</pre><p>So here is the script which gives us this resoult. After some modification we can get more universal version which can be suitable for different cases:</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class DetectCollisions : MonoBehaviour<br>{<br>    [SerializeField] private float _radius = 5f;<br>    [SerializeField] private float _power = 10f;<br>    [SerializeField] private float _upwardsModifier = 3f;<br><br>    private bool _exploded;<br><br>    private void OnCollisionEnter(Collision collision)<br>    {<br>        if (_exploded) return;<br><br>        if (collision.gameObject.CompareTag(&quot;Hazard&quot;))<br>        {<br>            _exploded = true;<br>            Debug.Log(&quot;We collided with Hazard object&quot;);<br><br>            Vector3 explosionPos = transform.position;<br>            Collider[] colliders = Physics.OverlapSphere(explosionPos, _radius);<br><br>            //A barrel can have several colliders, so push each Rigidbody only once<br>            HashSet&lt;Rigidbody&gt; pushed = new HashSet&lt;Rigidbody&gt;();<br><br>            foreach (Collider hit in colliders)<br>            {<br>                Rigidbody rb = hit.attachedRigidbody;   // &lt;-- the fix<br>                if (rb == null || !pushed.Add(rb)) continue;<br><br>                // Optional: only push barrels tagged Hazard<br>                if (!rb.CompareTag(&quot;Hazard&quot;) &amp;&amp; rb.gameObject != gameObject) continue;<br><br>                rb.AddExplosionForce(_power, explosionPos, _radius, _upwardsModifier, ForceMode.Impulse);<br>            }<br>        }<br>    }<br>}</pre><blockquote>Two things you may notice later:</blockquote><blockquote><strong>Explodes more than once:</strong> the falling barrel can hit several Hazard barrels, or bounce, so OnCollisionEnter runs again and adds another explosion. A bool _exploded check at the top of the method (like in my earlier version) makes it happen only once.</blockquote><blockquote><strong>Colliders on child objects:</strong> if a barrel’s collider is on a child object and the Rigidbody is on the parent, collider.GetComponent&lt;Rigidbody&gt;() returns null and that barrel won&#39;t move. collider.attachedRigidbody works in both cases.</blockquote><p>Next topic is about Trajectories we’ll explore it in 2nd part…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e062abd37acb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enemy AI]]></title>
            <link>https://medium.com/@yanvar103/enemy-ai-fb44c63efadb?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb44c63efadb</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 10:21:03 GMT</pubDate>
            <atom:updated>2026-08-31T10:21:03.383Z</atom:updated>
            <content:encoded><![CDATA[<p>First we build a scene like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3i5k3QefCikQaqzSuWgulA.png" /></figure><p>6 waypoints and floor. Way point is definad as prefab and has isTrigger enabled collider. So this will be our environment.</p><h3>AI Navmesh Baking</h3><p><a href="https://docs.unity3d.com/2021.3/Documentation/Manual/nav-NavigationSystem.html">Navigation System in Unity</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*1qQZAA_MXsPFQVsg.png" /></figure><blockquote>The Navigation System allows you to create characters which can navigate the game world. It gives your characters the ability to understand that they need to take stairs to reach second floor, or to jump to get over a ditch. The Unity <strong>NavMesh</strong><br> system consists of the following pieces:</blockquote><blockquote><strong>NavMesh</strong> (short for Navigation Mesh) is a data structure which describes the walkable surfaces of the game world and allows to find path from one walkable location to another in the game world. The data structure is built, or baked, automatically from your level geometry.</blockquote><blockquote><strong>NavMesh Agent</strong> component help you to create characters which avoid each other while moving towards their goal. Agents reason about the game world using the NavMesh and they know how to avoid each other as well as moving obstacles.</blockquote><blockquote><strong>OffMesh Link</strong> component allows you to incorporate navigation shortcuts which cannot be represented using a walkable surface. For example, jumping over a ditch or a fence, or opening a door before walking through it, can be all described as OffMesh links.</blockquote><blockquote><strong>NavMesh Obstacle</strong> component allows you to describe moving obstacles the agents should avoid while navigating the world. A barrel or a crate controlled by the physics system is a good example of an obstacle. While the obstacle is moving the agents do their best to avoid it, but once the obstacle becomes stationary it will carve a hole in the navmesh so that the agents can change their paths to steer around it, or if the stationary obstacle is blocking the path way, the agents can find a different route.</blockquote><p>Go to Windows/AI/Navigation, in inspector you see a new tab Navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*_-JOqsMhsrqEpusOyXhwZg.png" /></figure><p>Select your floors and set this options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*TIA_V2pw9HjQVEzX2Otoxw.png" /></figure><p>And bake it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*7inLq7-9nexwjl_5lH3i8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN7cBsravN-kSOHRMXlLWw.png" /></figure><p>Here is a navigation mesh, in bake tab there are some option to play with and rebake to see the result. I’ll keep default settings. Next is to set a navmesh agent.</p><h3>AI Navmesh Agent</h3><p>As AI I’ll create a simple sphere with some material, and add Nav Mesh Agent component to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Rc2k39VYM6Ge4uv3JI1cw.png" /></figure><p>After adding this component you can see a cylinder in viewport(I made floor darker to see it)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*qOydgmGv5uDN0qvMoqnKSg.png" /></figure><p>When Base Offset is 0.5 object is right on the floor, if we increase it it will be above the floor(hover up). if we decrease it it gets inside the floor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGTiJLcR8YxC7epndsZMiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_kJb1CqOhSLa4eI9otJzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AerL_AGzcUMHDHGGfzLfog.png" /></figure><p>You can also check other settings on your own</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*Ekphdv2ybcKmpwgO5ma89A.png" /></figure><h3>Challenge: Random Waypoint</h3><p>Let’s add an AI script to our AI object. We want AI to go to the random WayPoint at start.</p><p><a href="https://docs.unity3d.com/ru/530/Manual/nav-MoveToDestination.html">Telling a NavMeshAgent to Move to a Destination</a></p><p>According this manual we will write the script. We have to store all wayPoints first in list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*l991DYNN82WrFkKHQv6Wlg.png" /></figure><p>Also we need a reference to navmeshagent, you can find it if you use UnityEngine.AI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*Squx5rrl0RzaKpyhwJmJIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dG_w_2w4vq1dZxfoWhvoqQ.png" /></figure><p>So then we give it a random destination at start</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8xefuvPwecg1tdMZ3x9lA.png" /></figure><p>Don’t forget to add them in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*z31dlmfKjTgRSKQfx2JGkA.png" /></figure><h3>Challenge: Smart AI</h3><p>You can also make make movement by point sequence and change it’s order by dragging right in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*1P-foS9O-P_KQ9ntCAkUSw.png" /></figure><p>We already made it move to 1st point at start, to move it to the next destination first we need to know did object reached the destination, we need to check the distance. In you search for distance in NavMeshAgent Part of Unity manual you can find this command: ramining distance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVh0p_7WMJTL4G2BNBd2dA.png" /></figure><p>Now we can check it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*KtC4hwwfviytJPZdXhNTBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*yESDJN5yk2m363ua5yBSTg.png" /></figure><p>If I want to stop it at some distance I can type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*5rcgvPgDvW-h2Kz-VkCpYw.png" /></figure><p>Now we set the next destination inside if statement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*5B95udBKh3zHfKv07y3PFg.png" /></figure><p>But it breaks when it reaches the final destination. To loop it we simply manipulate with _currentPoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*G2Sgowhh5haGNgg0mT6EEA.png" /></figure><p>Let’s say I want to move it with opposite direction if it reaches the final diestination. In here we add a bool check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyMCUSZjIWPM_clb0GRBCA.png" /></figure><p>After cleanup</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.AI;<br><br>public class AI : MonoBehaviour<br>{<br>    [SerializeField] private List&lt;Transform&gt; _wayPoints; //list of wayPoints<br>    private NavMeshAgent _agent; //reference<br>    private int _currentPoint = 0;<br>    private bool _reverseMode = false;<br><br>    void Start()<br>    {<br>        _agent = GetComponent&lt;NavMeshAgent&gt;();//find the component<br>        if(_agent != null)<br>        {<br>            //int _randomIndex = Random.Range(0, _wayPoints.Count);//getting random point from list<br>            _agent.destination = _wayPoints[_currentPoint].position;<br>        }<br>    }<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        CalculateAIMovement();<br>    }<br><br>    private void CalculateAIMovement()<br>    {<br>        if (_agent.remainingDistance &lt;= 1f)<br>        {<br>            if (_reverseMode == true) _currentPoint--;<br>            else _currentPoint++;<br><br>            if (_currentPoint == _wayPoints.Count - 1) _reverseMode = true;//-1 because count starts from 0;<br>            else if (_currentPoint == 0) _reverseMode = false;<br><br>            _agent.SetDestination(_wayPoints[_currentPoint].position);<br>        }<br>    }<br>}</pre><h3>Introduction to FSM</h3><p>A <strong>Finite State Machine (FSM)</strong> is an architectural design pattern that ensures a GameObject can only exist in <strong>one state at a time</strong> (e.g., Idle, Walk, Jump, Attack). It eliminates complex, hard-to-read “if-else” or switch-statement structures by separating individual state behaviors into their own clean classes.</p><p>Here you can read more about FSM from <a href="https://medium.com/@rogermoore06?source=post_page---byline--3486dc42644e---------------------------------------">Roger moore</a></p><p><a href="https://medium.com/@rogermoore06/fsm-in-unity-to-create-smart-ai-3486dc42644e">FSM in Unity to Create Smart AI</a></p><h4>Core Concepts of an FSM</h4><p>An FSM consists of three main elements:</p><ul><li><strong>States:</strong> The specific condition or behavior of an entity (e.g., <em>Idle</em>, <em>Walking</em>, <em>Jumping</em>, <em>Attacking</em>).</li><li><strong>Transitions:</strong> The rules or conditions that allow the entity to move from one state to another (e.g., switching from <em>Idle</em> to <em>Jumping</em> when the spacebar is pressed).</li><li><strong>Inputs/Events:</strong> The triggers — like player actions or timer expirations — that evaluate the transition rules.</li></ul><h4>Common Uses in Games</h4><ul><li><strong>Non-Player Character (NPC) AI:</strong> Controlling enemy routines like patrolling an area, chasing the player, or retreating when low on health.</li><li><strong>Player Animations:</strong> Ensuring a character plays the correct animation and preventing impossible moves (like attacking while in the middle of a jump).</li><li><strong>Game Modes:</strong> Managing the high-level flow of the game, such as transitioning between the main menu, active gameplay, pause screens, and game over states.</li></ul><h4>Pros and Cons</h4><ul><li><strong>Pros:</strong> They are fast, lightweight, predictable, and very easy to visualize and debug.</li><li><strong>Cons:</strong> They can become messy (“spaghetti code”) and hard to scale when a game grows to include too many complex, overlapping behaviors.</li></ul><p>This design pattern is made of 2 basics Enums and Switch statement.</p><p>Enums store all states and allows us to see and change it in inspector even in run time, In switch statements we define what this NPC do in each state.</p><p>It is a vicious circle for NPC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l_IOMG3OsEb_oO2O.jpg" /></figure><p>Let’s add it to our AI, first we define some statements</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NH6E9BWGJShPv-DbXkVvQ.png" /></figure><p>We also can change them in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*SNG8u0q6w_17-ZktMgDcxg.png" /></figure><p>Now let’s determine their behavior using switch statement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*UKBqhhQ4wkQ7Q9T6zwMudQ.png" /></figure><p>In practice while prototyping you will have this kind of scheme to build the logic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*fXehrWfqauQp6y0tCwUw8w.png" /></figure><p>Let’s implement this to our AI. So here we are starting with Walking, we will call our CalculateMovement() in this state. Next is Juming, it requires user input, let’s use new input system(using UnityEngine.InputSystem)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*86FYMTIrAzRoyDUuJdvQRw.png" /></figure><p>Next is Attack state. In this state I want AI to wait 3sec and go back to walking state(continue walking).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7vt5WiwWmxqtUlUNnzixw.png" /></figure><h3>Generating Offmesh Links</h3><p>Let’s create another separate floor in some distance from existing floor, chose it and rebake navmesh, also add a new point there PointG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*R2l3ReM3065c2NUPDoZbOQ.png" /></figure><p>I’ll add this point to AI WayPoints in inspector. What happen if I test it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*rXq4PhA3LWZDxJdoZA3D1w.png" /></figure><p>It stopped at the edge, couldn’t reach point G and go back to it’s routine.</p><p>Here OffMeshLinks help us ot move the agent to another side where is Point G. Let’s add it. Select the new floor and add a component, define start and end as points F and G</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*lWIkt9CjzbIRtPzoh0Q4gQ.png" /></figure><p>Now it can pass the abyss.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb44c63efadb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GME 301: Game Logic & Interactions I. Raycasting.]]></title>
            <link>https://medium.com/@yanvar103/gme-301-game-logic-interactions-i-raycasting-160cfa1a0dbd?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/160cfa1a0dbd</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 05:23:04 GMT</pubDate>
            <atom:updated>2026-08-27T05:23:04.139Z</atom:updated>
            <content:encoded><![CDATA[<p>Raycast is basicly a 3d line in 3d space, beeing able to dectact the intersection points with colliders in scene, bullet holes on walls in FPS games, interactions with items when you aiming with cursor are all managed by raycasting. We can unlock solutions for lots of different game mechanic tasks via raycasting.</p><p>For this course we use the latest aviable version of Unity 2020. Now it is 2020.3.48f1(check also WebGL Build Support).</p><p>You can check the documentation about Raycasting here, when you read it no need to go deep in exapmles, just focus on how to use raycast, about syntax and what it requires to make it work.</p><p><a href="https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Physics.Raycast.html">Physics.Raycast</a></p><p>As first example we are going to create a scene with one object(cube) and an ability to click on it by mouse button and assign it a random color.</p><p>First we create a Player class and assign it the main camera. So the task requires user input(left mouse click). According to the documentation Raycast has some options: ray origin, direction and hit. First we must find out the origin. It can be a main camera or mouse position.</p><p>Install input system package, restatrt Unity and add to player using UnityEngine.InputSystem library.</p><p>Now we can use New Unity Input System and add user left mouse button input</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br>public class Player : MonoBehaviour<br>{<br>    private void Update()<br>    {<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Debug.Log(&quot;left mouse button clicked!&quot;);<br><br>        }<br>    }<br>}</pre><p>Next this is to find out ray start point(origin). It must be our mouse position in screen. Here in documentation you can find how to make it</p><p><a href="https://docs.unity3d.com/6000.1/Documentation/Manual/CameraRays-cast.html">Cast a ray from a camera</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*GLBAP1a7e6bem7r-iJIcOw.png" /></figure><p>Here it says we need Vector3 position, but mouse.current.position returns Vector2Control, so we use ReadValue() from Mouse.current.position</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*VouRcTaqAsMOX60uxs_Uqw.png" /></figure><pre>Vector2 _mousePosition = Mouse.current.position.ReadValue();<br>Ray _rayOrigin = Camera.main.ScreenPointToRay(_mousePosition);</pre><p>After we define a hit object, and fire a raycast using if statement, you can see there 16 options of using raycast, we will use 3rd one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*G5bqM3cTgoOLco-8ZZyypQ.png" /></figure><p>We need to get access to the hit object and do something with it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KPH4I6vBy7hZoojLoHu8g.png" /></figure><p>It must give us name of cube</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*ek8M4XPYGmxAuR7f5IU-fQ.png" /></figure><p>Once we successfully hit the object using raycast, now we can change it’s color</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br>public class Player : MonoBehaviour<br>{<br>    private void Update()<br>    {<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Debug.Log(&quot;left mouse button clicked!&quot;);<br>            //defind the origin<br>            Vector2 _mousePosition = Mouse.current.position.ReadValue();<br>            Ray _rayOrigin = Camera.main.ScreenPointToRay(_mousePosition);<br>            //define the hit object<br>            RaycastHit _hit;            <br>            //fire the ray<br>            if(Physics.Raycast(_rayOrigin, out _hit))<br>            {<br>                Debug.Log($&quot;hit: {_hit.collider.name}&quot;);<br>                <br>                Collider _hitObject = _hit.collider;<br>                if(_hitObject.GetComponent&lt;MeshRenderer&gt;() != null)//meshRenderer null check<br>                {<br>                    _hitObject.GetComponent&lt;MeshRenderer&gt;().material.color = UnityEngine.Random.ColorHSV();//assign a random color<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Tested, it’s working, we successfully casted our first Ray.</p><h3>Challenge: Multiple Objects</h3><p>Let’s say we have multiple different objects in our scene(cube, sphere, capsule, etc.), when we click left mouse only cube type objects must change the color. So we need to check or access it’s shape</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br>public class Player : MonoBehaviour<br>{<br>    private void Update()<br>    {<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Debug.Log(&quot;left mouse button clicked!&quot;);<br>            //defind the origin<br>            Vector2 _mousePosition = Mouse.current.position.ReadValue();<br>            Ray _rayOrigin = Camera.main.ScreenPointToRay(_mousePosition);<br>            //define the hit object<br>            RaycastHit _hit;            <br>            //fire the ray<br>            if(Physics.Raycast(_rayOrigin, out _hit))<br>            {<br>                Debug.Log($&quot;hit: {_hit.collider.name}&quot;);<br>                <br>                Collider _hitObject = _hit.collider;<br>                Mesh _mesh = _hitObject.GetComponent&lt;MeshFilter&gt;().mesh;<br>                if (_hitObject.GetComponent&lt;MeshRenderer&gt;() != null &amp;&amp; _mesh.name == &quot;Cube Instance&quot;)//meshRenderer null check and also checked it&#39;s mesh name<br>                {<br>                    Debug.Log($&quot;Selected mesh is type of {_mesh.name}&quot;);//here I get it&#39;s name, it called Cube Instance<br>                    _hitObject.GetComponent&lt;MeshRenderer&gt;().material.color = UnityEngine.Random.ColorHSV();//assign a random color<br>                }<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NP9XRtU2D867n18eCt3pdA.png" /></figure><p>It worked. But there is another way to do this using tag system. We tag all cube objects as Cube, also add another tags (sphere, capsule), also tag them. Then use this script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br>public class Player : MonoBehaviour<br>{<br>    private void Update()<br>    {<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Debug.Log(&quot;left mouse button clicked!&quot;);<br>            //defind the origin<br>            Vector2 _mousePosition = Mouse.current.position.ReadValue();<br>            Ray _rayOrigin = Camera.main.ScreenPointToRay(_mousePosition);<br>            //define the hit object<br>            RaycastHit _hit;            <br>            //fire the ray<br>            if(Physics.Raycast(_rayOrigin, out _hit))<br>            {<br>                Debug.Log($&quot;hit: {_hit.collider.name}&quot;);<br>                Collider _hitObject = _hit.collider;<br><br>                //Mesh _mesh = _hitObject.GetComponent&lt;MeshFilter&gt;().mesh;<br>                /*if (_hitObject.GetComponent&lt;MeshRenderer&gt;() != null &amp;&amp; _mesh.name == &quot;Cube Instance&quot;)//meshRenderer null check and also checked it&#39;s mesh name<br>                {<br>                    Debug.Log($&quot;Selected mesh is type of {_mesh.name}&quot;);//here I get it&#39;s name, it called Cube Instance<br>                    _hitObject.GetComponent&lt;MeshRenderer&gt;().material.color = UnityEngine.Random.ColorHSV();//assign a random color<br><br>                }*/<br><br>                if (!_hitObject.GetComponent&lt;MeshRenderer&gt;()) return;<br>                switch(_hitObject.tag)<br>                {<br>                    case &quot;Cube&quot;:<br>                        _hitObject.GetComponent&lt;MeshRenderer&gt;().material.color = Random.ColorHSV();<br>                        return;<br>                    case &quot;Sphere&quot;:<br>                        //do nothing<br>                        return;<br>                    case &quot;Capsule&quot;:<br>                        //do nothing<br>                        return;<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Don’t forget to set the tag in inspector.</p><h3>Challenge: Click to Instantiate</h3><p>In a new scene we create a floor(as scaled cube). Place the main cam in a convenient place. Create a sphere prefab. When we click on cube, on that place of Cube must be instantiated sphere prefabs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*fHjtZdPP1EfQ3JJKTRDK4w.png" /></figure><p>to get the point of intersection of ray to the object we use _hitInfo.point</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class PlayerInstantiate : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _spherePrefab;<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        //if left mouse click<br>        //raycast(origin - mouse position)<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Vector2 _mousePosition = Mouse.current.position.ReadValue();<br>            Ray _rayOrigin = Camera.main.ScreenPointToRay(_mousePosition);<br><br>            //hitInfo(detact the floor point)<br>            RaycastHit _hitInfo;<br>            if (Physics.Raycast(_rayOrigin, out _hitInfo))<br>            {<br>                //instantiate prefab at hit point<br>                GameObject _sphere = Instantiate(_spherePrefab, _hitInfo.point, Quaternion.identity);<br>            }<br>        }<br>    }<br>}</pre><p>Now we can place pherese on that place of the floor where we click on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*44mp9mLPfrtwij4Pd91ZSw.png" /></figure><h3>Layer Mask in Unity</h3><p>Layer masks with raycast we can use for example in FPS games when we have an option ”friendly fire”, it means only GameObjects which are in enemy layer can get a damage. layermask is a 32 bit integer</p><p><a href="https://docs.unity3d.com/6000.5/Documentation/ScriptReference/LayerMask.html">LayerMask</a></p><p>This gives us ability to separate Raycasting GameObjects by layermask.</p><p>Let’s create 3 objects: 3 enemies, 1player and layers for them in inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlIhdnMT2yVV83pdDVwOZA.png" /></figure><p>bigger one is player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*IF2goFzhAq0Lc7IRU0yD9A.png" /></figure><p>When we click on an object it must turn only enemy object’s color to red.</p><p>In here we use Physics.Raycast with these parametres</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*IirF5fvNcBWiaIF155vNyg.png" /></figure><p>1 &lt;&lt; 6 meand if 6-layer in 1 which means enable. This is full script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class PlayerMask : MonoBehaviour<br>{<br>    <br>    // Update is called once per frame<br>    void Update()<br>    {<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Ray _rayOrigin = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());<br>            RaycastHit _hitInfo;<br>            if(Physics.Raycast(_rayOrigin, out _hitInfo, Mathf.Infinity, 1 &lt;&lt; 6))<br>            {<br>                _hitInfo.collider.GetComponent&lt;MeshRenderer&gt;().material.color = Color.red;<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*nGDXfyMyqAAvS0_vPJTe7w.png" /></figure><p>If I want to if statement also Player layer I’ll type this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*dHu3WBKuCd05qcBlRu8LJQ.png" /></figure><p>here | means or. Now player also can be turned to red.</p><p>We also can set masks in inspector as a variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glJ8JCKznjljgkTJh0goKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*6wLerlG1cDTrGx_31aRA0Q.png" /></figure><h3>Challenge: Directional Rays</h3><p>Untill this point we considered the case where raycast has only origin point, which is mouse position, now we are going to use Raycast with custom direction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*9YsJLTOotYbwZfPNNGFr6A.png" /></figure><p>Let’s create a sphere with attached to in sphere script and a floor. Sphere collider with enable gravity, we give this sphere a ray with direction down and with length of 1f. When we press 1 it is going to fall and must stop falling when ray touches the floor, sphere must stay at position 1f above the floor. We also will make the ray visible using Debug.DrawRay method. According to the task as we are going to control the sphere’s gravity option we also have to get access to it’s Rigidbody component.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class Sphere : MonoBehaviour<br>{<br>    private Rigidbody _rigid;<br><br>    private void Start()<br>    {<br>        _rigid = GetComponent&lt;Rigidbody&gt;();<br>    }<br><br>    void Update()// Update is called once per frame<br>    {<br>        Debug.DrawRay(transform.position, Vector3.down * 3f, Color.red); // add a visible ray in viewport and play window<br>        if(Physics.Raycast(transform.position, Vector3.down, 3f))<br>        {<br>            _rigid.useGravity = false;<br>            _rigid.isKinematic = true;//no forces act on this object<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6YSjQMNEuCdbXE9nREvlmw.png" /></figure><p>Here it is, sphere stops falling 3f above the floor, turning the gravity to false.</p><p>We can also add in it out hitInfo using Raycast option 12, so we can get the information about hit object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*pw0lkysTx_P3bxxCP_sRdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sSfLv0qEt5e25-kuK62mw.png" /></figure><h3>Challenge: Bullet Holes</h3><p>Let’s use Raycasting to instantiate bullet holes on the shooting wall. First we prepare the scene. Here I created wall, floor as cube, imported GDHQ character, target Crosshair textures, bullethole textures. Deleted existing main camera as imported GDHQ_FPS_Controller has it’s own main camera(don’t forget to set it’s tag to main camera). Project settings/Player — Active Input Handling must be set to both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCZxjoyB19ekwol0Tu1RIw.png" /></figure><p>We want left mouse click to shoot. In imported FPS_Controller class there is no anything to mouse click or to shoot action. So we are going to create a separate class to implement shooting by left mouse click and use raycast in it. I’ll call it Shoot script.</p><p>Let’s define a variable fo bullt hole, here are 4 different prefabs and I want to use all of the by instantiating randomly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*D5jp1epNlK9IhhdkujFgRA.png" /></figure><p>Here is a little bit different origin of raycast using UI element(Crosshair). For this case we use method ViewPortPointToRay and as a new Vector3 we find the center of the screen which is (0.5f, 0.5f, 0)</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class Shoot : MonoBehaviour<br>{<br>    [SerializeField] private GameObject[] _bulletHolePrefabs;<br>    [SerializeField] private LayerMask _mask;<br>    <br>    void Update()<br>    {<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Ray _rayOrigin = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));<br>            RaycastHit _hitInfo;<br>            <br>            if(Physics.Raycast(_rayOrigin, out _hitInfo, Mathf.Infinity, _mask))<br>            {<br>                int _randomIndex = Random.Range(0, _bulletHolePrefabs.Length);<br>                GameObject _bulletHole = Instantiate(_bulletHolePrefabs[_randomIndex], _hitInfo.point, Quaternion.LookRotation(_hitInfo.normal));<br>            }<br>        }<br>    }<br>}</pre><p>I also used Layer mask, so it instantiates only if Raycasting object is in Wall layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIZ1JilmLQYYlqR6-CjDuA.png" /></figure><p>Here you can see z axis conflct on textures. To avoid it you can just make collider’s size little bit bigger than mesh size. So the main logic works.</p><h3>Challenge: Click to Move</h3><p>Let’s say we have a floor, and a Player object, we want Player move to that point where we click on floor plane. So in here we need 2 scripts, Pointer and Player. Pointer will be attached to MainCamera, PlayerToMove script to Player object. We will use Raycast to determine the point on floor plane and communicate with Player script to move it to that point.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class Pointer : MonoBehaviour<br>{<br>    private Vector3 _point;<br>    private PlayerToMove _player;<br><br>    private void Start()<br>    {<br>        _player = FindObjectOfType&lt;PlayerToMove&gt;();<br>    }<br><br>    void Update()<br>    {<br>        if(Mouse.current.leftButton.wasPressedThisFrame)<br>        {<br>            Ray _rayOrigin = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());<br>            if(Physics.Raycast(_rayOrigin, out RaycastHit _hitInfo))<br>            {<br>                if(_hitInfo.collider.name == &quot;Floor&quot;)<br>                {<br>                    _player.UpdateDestination(_hitInfo.point);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>It communicates to PlayerToMove and updates it’s _destination every frame. In PlayerToMove script Player moves according to _destination</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class PlayerToMove : MonoBehaviour<br>{<br>    private float _speed = 5f;<br>    [SerializeField] private Vector3 _destination;<br>    <br>    void Update()<br>    {<br>        float _distance = Vector3.Distance(_destination, transform.position);<br>        Debug.Log(&quot;Distance: &quot; + _distance);<br>        <br>        if (_distance &gt; 1f)<br>        {<br>            Vector3 _direction = _destination - transform.position;<br>            _direction.Normalize();<br>            transform.Translate(_direction * _speed * Time.deltaTime);<br>        }<br>    }<br><br>    public void UpdateDestination(Vector3 _pointer)<br>    {<br>        _pointer.y = 1f;<br>        _destination = _pointer;<br>    }<br>}</pre><p>_distance is important here. It decides to move, we can decrease if statement to 0.1f. If you set it to exact 0, it always tries to move every frame even while you don’t click and will look like shaking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=160cfa1a0dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity Input System]]></title>
            <link>https://medium.com/@yanvar103/unity-input-system-1ae3efc5b1ed?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ae3efc5b1ed</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 13:03:19 GMT</pubDate>
            <atom:updated>2026-08-12T13:03:19.489Z</atom:updated>
            <content:encoded><![CDATA[<p>For software engineers the best way to learn something new is by reading it’s documentation, not by youtube or other learning videos. It gives us an ability to figure out it qiuck without wasting time watching 30–45 min videos. Here is an Unity Input System documentation</p><p><a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@1.20/manual/index.html">Input System</a></p><p>First we install Input System from package manager(we can click yes to activate new input sytem), after Unity restarts, we go to Edit/Project settings/Player and set Active Input handling to both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*GWLSPBLbjOHEEaYdkFQWQQ.png" /></figure><p>Now old and new Input systems are active.</p><h3>Create Input Asset</h3><blockquote>Actions</blockquote><blockquote><strong>Actions</strong> allow you to separate the purpose of an input from the device controls which perform that input, and associate the purpose and device controls together in a flexible way.</blockquote><blockquote>For example, the purpose of an input in a game might be to make the player’s character move. The device control associated with that action might be the left gamepad stick.</blockquote><p>Let’s create a new folder Input in Assets and create an Input Action in it and name it PlayerInputActions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*RP3VBy9Lka_2vY1SuQBCGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*Ro4AGwmuVMsv1weMlXQQ-w.png" /></figure><h3>Action Maps</h3><p>When you click edit asset Unity opens a new window which has Action maps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxZFPV0B1VYIdfxjFWeyYQ.png" /></figure><blockquote>Action maps provide a way to group collections of Actions that represent different input scenarios in your project (such as UI navigation, gameplay, etc.)</blockquote><blockquote>Actions must belong to an action map, therefore if you are starting with an empty Actions Asset, you must create an action map before you can create any actions.</blockquote><blockquote>The Action Maps section on the left side of the <a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@1.20/manual/actions-editor.html">Actions Editor window</a> allows you to create, rename, delete, and duplicate action maps.</blockquote><p>For example, in GTA game when you walk or run you have one controls for walk, when you drive a car or fly in helicopter you have another input controls for each, they are actually action maps which stores these control settings. Every game has a pause mode, it also has it’s own action map, when you press W, S keys it switches between menu items. Every scenario has it’s own Action map. It allows different key bindings for different actions. You can only have one action map enabled at a time.</p><p>This is how it look in action maps window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*604UIPCdKV7_5u9O8tnxHQ.png" /></figure><p>Let’s create our first action map. When you create an Action map it auto creates default New Action in it. I recommend you to delete it and create new one from scratch by pressing + button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*EBeT_RbbDrHvC4jyorvTYg.png" /></figure><p>This action creates an empty default Binding, which I recommend to delete. Let’s set this action as Fire in space shooter. In properties we set it as button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUk9GPBrNd-VjVGq-XnYKw.png" /></figure><p>Then add a simple binding from scratch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*hzka-pgaFpafuJCr2OFa3w.png" /></figure><p>In binding properties we can set the path as Keyboard/By Location of Key/Space or just click on Listen button and press Space key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*aecL47F0_SHy1bwJJ3qkHA.png" /></figure><p>It automatically finds it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*6n4cmSRC_gytQdYsCXJw0A.png" /></figure><p>Now the Space key triggers our Fire action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VX3WfZQJUbyffUw2M0ZPVg.png" /></figure><p>You can save your asset manually or check the auto save</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mq7EcL_m9cgriaH83w607Q.png" /></figure><p>I recommend you to save manually, because auto save always forces Unity remcompiles, which is annoying.</p><p>Next we see how to read these inputs.</p><h3>Challenge: Dog Input Action</h3><ol><li>bark action — space key</li><li>walk action — WASD keys</li><li>run — LShift(held down more than 1 sec)</li><li>die — D + F(pressed at the same time)</li></ol><p>So 1st is simple as fire we did earlier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9buNuNYfU_I2fZrySwydA.png" /></figure><p>2nd must be a value and control type 2D vector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*PZCr0oULB-U92sOK4pyTKg.png" /></figure><blockquote>Adds a 2D axis composite binding that represents a 4-way button control like the D-pad on gamepads. Each button sub-binding represents a cardinal direction, is most useful for representing up-down-left-right controls, such as WASD keyboard input. It is implemented in the <a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@1.20/api/UnityEngine.InputSystem.Composites.Vector2Composite.html">Vector2Composite</a> class. The output is a Vector2. This composite&#39;s <a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@1.20/manual/binding-properties-panel-reference.html"><strong>mode</strong> property</a> allows you to choose whether the inputs should be treated as digital or analog controls.</blockquote><p>We add a binding for it as 2d composite</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*MdqGUdkbnjwGoJvdLNrvjQ.png" /></figure><p>Then we give them paths</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*3uJt6caZ4MXuKBFU8CNrSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*UNm3FsnVXxplFOssmkKNAA.png" /></figure><p>Walk is ready, let’s set the run action</p><p>For run we use Button action and simple binding with path LShift. But in here we need this button to be held for 1 sec. For this we add here a bult in interaction — Hold</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQ7Vu5TTxPz0Jwcmvo0xCQ.png" /></figure><p>More about built in interaction here you can see in documentation:</p><p><a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@1.20/manual/built-in-interactions.html">Built-in interactions</a></p><p>You can also write your own custom interaction.</p><p>This hold interaction has it’s parametres</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*rp49xKOzGxEsKc3_FBaVAQ.png" /></figure><p>This is an explanation of press point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*Kfon8e3qhJ9vnUgo3GVLRg.png" /></figure><p>We set the hold time to 1 by task.</p><p>Next is Die action with 2 buttons, for this we use a special binding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*13sG33UQibAkZ3lYxp9XMw.png" /></figure><blockquote>This composite can be used to require another button to be held while pressing the button that triggers the action. This is most commonly used on keyboards to require one of the modifier keys (shift, ctrl, or alt) to be held in combination with another key, e.g. “CTRL+1”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*Vi55AMmpzZQq2e3XdH5C1w.png" /></figure><p>Now the task is completed, don’t foreget to save the asset.</p><h3>Scripting New Input System</h3><h3>Bark input</h3><p>After editing and saving the asset we can generate a C# Class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*PrjnxRAK9wT5jLNKYx66GA.png" /></figure><p>Generating a <strong>C# class for Input Actions</strong> turns your Input Action asset into strongly-typed code you can access directly, instead of using string names.</p><p>Without generated class (string-based, error-prone):</p><pre>InputAction _moveAction = _playerInput.actions[&quot;Move&quot;]; // typo risk!<br>Vector2 _move = _moveAction.ReadValue&lt;Vector2&gt;();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Furl7s9QfVF90TuFIji4FQ.png" /></figure><p>So we are creating C# class, no need to change these settings, click apply</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*-VFj_yfNEf4C22mvxMhKqg.png" /></figure><p>It creates a script in the same asset folder. It is a little bit gibberish for us, we don’t get inside this script and modify something, it is just for getting access to action maps. If we modify the action map in editor and save it, this script updates automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*aej5MY-kX8CQxdmR6JkLYg.png" /></figure><p>Let’s create a cube as Player(Dog) and a Monobehaviour script(PlayerInput) for it and start interact with these bindings. Let’s open it and add InputSystem library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*0jVOAAUigK_5BLL1bFVqsA.png" /></figure><p>Here to work with action maps we need to pass 3 steps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*ve3Aq45Q1jH_auRt5GGz8w.png" /></figure><p>The syntax of delegets and events we use here is new for us.</p><p>After 1st step you see we have an access to actions in it. We easily can get them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*xQuUOrGmH8RMCnfyXqDMOA.png" /></figure><p>We enable this action which is step 2. And you see we also have an access to actions in it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*6FLrJdoZvSnxoQnpUzLv4A.png" /></figure><p>Here(in 3rd step) we define what will happen when this action trigger. For example, bark(after pressing space key).</p><p>We have some commands with action: started, performed, exited, cancelled, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*9bNyHbmYLzyuKdPzgdaq5w.png" /></figure><p>You see they have a special lighting sign, they are action events(System.Action). let’s select performed type +=</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*SwjkYmoqL9fiogjn6JqdcQ.png" /></figure><p>Here if we press tab Unity automatically creates a new method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*4oz4ClXhtTUq2VmMolpCuQ.png" /></figure><p>This method will be called if this event is performed. And inside this method we define what must happen,</p><p>Let’s give a message and readout what is inside CallbackContext(let’s rename it context(instead of obj))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*JNkE3auGQ6PnpI26t47ESw.png" /></figure><p>Now let’s test. It works, if we press Space in Game mode we see this message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pFAPXegW2zG-DT_vrvcTw.png" /></figure><p>Earlier we used Input commands like Input.GetKeyDown, Input.GetKeyUp etc. Let’s compare <strong>old Input System</strong> (Input.GetKey) vs <strong>new Input System</strong> (Action/callbacks). Old Input Sytem checks every single frame → “is key pressed right now?” New Input System with generated C# class + events<strong> Subscribe using </strong><strong>+= (event-style): </strong>No Update() checking needed! Function only runs WHEN the event happens (key pressed)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*uCk5UOh0EY2CihXwDmK2Fg.png" /></figure><p>For <strong>continuous input</strong> (movement, look direction) you still read values in Update(), but for <strong>discrete actions</strong> (jump, fire, interact) events (+=) are cleaner!</p><p>How we know is dog done barking, for this we use cancelled command as before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*8KGtUQWdQZVYLcmbXobJ1A.png" /></figure><p>Let’s test it, if I press the Space key it must say barking… one time, after I lift up the Space key it must say Barking Done(like GetKeyUp).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwBualhiO4giMnasNAeleg.png" /></figure><p>We also can use started command, for example, in charging moments, when player holds the key, and something must start charging while he holds the key. In most we use performed command.</p><h3>Walk Input</h3><p>We add it as before by performed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*7ZLTB_YYEHNMxP7zQrFo_w.png" /></figure><p>If we test it we can see what happens when we press WSAD buttons</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2ienGEzdbcqb5HHQm5Hhw.png" /></figure><p>It determines the 2D Vector direction. If I press W+D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omVdqA17nBc_DWrZVb61NQ.png" /></figure><p>It gives us this direction: middle between right and forward directions.</p><h3>Run Input</h3><p>We add it as before by performed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*GN9TWxtA0DfOdfEaZLThxA.png" /></figure><p>Leter we will combine walk and run</p><p>But here we also need to cancel the run after Player lift up the L shift button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*1b1IP2c_XzJwpP2OSeB8zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGYPhZk4q2UV7HEfu8Jb3g.png" /></figure><h3>Die Input</h3><p>Let’s set it as before and test it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*a00jdiVZoglrSg1cJ2bDzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rNMXa00aJxskuLceuN_AQ.png" /></figure><p>You here we pressed D holding F, so it moved right by D and dead. This happened because my D key is already busy by Walk action. You can change Binding to another buttons, save the asset, C# class will update automatically and it will work.</p><p>We can also add our custom method for the same Action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*DykI050_s43VKzON_zxAVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VEQvuelOQSdHmfTObwHKg.png" /></figure><h3>Smooth Movement</h3><p>Let’s create new InputActions, generate C# script and a script to register action events of Player Movement from scratch.</p><p>Renamed previus Input files and script to Dog(instead of Player) and created new PlayerInputAction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*6k-uqnDwdxbs0kpSHPsFmQ.png" /></figure><p>Renamed these lines in script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*uU-W-aXLnhJI7UlJk49i9A.png" /></figure><p>Here is a new action map</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsOYxniJn-hRp2hDz3Lyrw.png" /></figure><p>Added new Player object and script for it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*WXf9to5e3TLqDBrt74tGUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*JeaEGsr1YeOKfEUhRXwtMg.png" /></figure><p>Everything are the same as before, now we need to register the action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*BYr4ZcrgrMcFWg7wIEBlgA.png" /></figure><p>$ — string interpolatio, $ before a string = lets you insert variables directly inside {}. Here we grabbed Vector2 x,y values from context. Let’s test what we got</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*KsOZ9YDY-6cyWFa9oIk5SA.png" /></figure><p>Before I disabled DogInputs for testing(or deactivate the Dog object)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*ZmyaJHYcdPeYPRQSTni4dA.png" /></figure><p>Let’s map this to our Player object movement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*rLjwNtV8M6oDD47ISNi6MQ.png" /></figure><p>In here var = “let the compiler figure out the type automatically”(we also can type Vector2 insted of var)</p><p>Now let’s check it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*8sd1cHAjeOjLRMmm1eoHQQ.png" /></figure><p>It moves once when we press the key, it doesn’t move continuous when we hold the key, because the movement runs after action is happened(performed). For these type of cases we instead of performing we poll and check Inputs every frame, we use void update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*X2G-utamlqJLwLEABgnjUw.png" /></figure><p>With this way we get smooth continuous movement. Now it moves in XY plane, If we want to move it in XZ place</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*1_kAgaCKEOQZ-EUvpI-EMw.png" /></figure><p>We have full controll readValue of this action.</p><h3>Challenge: Random Color</h3><p>When you press Space button random color is assigned.</p><p>Let’s create a new action map in existing PlayerInputActions asset for this and save it(C# script auto updates)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYmcE9u86v3V467Mizoi_A.png" /></figure><p>we initialize it in existing PlayerInput script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*5YNgxkiOI8OGvsAOoZGSRw.png" /></figure><p>I’ll tested, it works</p><h3>Challenge: Rotation</h3><p>If A(or left arrow) key is pressed and held, rotate to the left</p><p>If D(or right arrow) key is pressed and held, rotate to the right</p><p>I’m going to do it in existing Action map, and as my A and D keys currently are busy I’d like to use, for example, Z and C keys. Logic is the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3c9393H04GWPdW-BicEYg.png" /></figure><p>I also added positive/negative bindings 2 times(for Z and C, 2nd is for alternative arrow keys)</p><p>We save asset and go into PlayerInput script, Let’s try to see the context</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhJZ8MOrg703DYMTfJPxNw.png" /></figure><p>It works, now let’s try to actually rotate the Player with it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*P2Fg9R8IasdtigwfcL-_og.png" /></figure><p>After testing, I noticed that the rotation works inverted, if I press left arrow key(or Z) it turns right. In Binding properties we have Preocessors, here we can invert binding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQSUY0KGAZ-Gy-hvUE0dzw.png" /></figure><p>We add it for both rotation 1D axis bindings and save. After this rotation works correctly.</p><h3>Challenge: Action Map Swap</h3><p>Create an action map for driving and switch to it via “T” key. We should be able to move in 3D space(left, right, forward, backward).</p><p>For this challenge I restructured PlayerInputActions, I combined PlayerWalk, material(color) and Rotation action maps, and created a new separate Drive action map</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RtYqpsF3XsMeHKAIiFDcA.png" /></figure><p>Added a movement action to drive action map</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5jbqb7et1NEw85SFUnHzA.png" /></figure><p>We add a new action in PlayerWalk action that switches action maps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av3hA3zS1keVg9qEY-poTQ.png" /></figure><p>Let’s save it and do some changes in PlayerInput script according to the new structure</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class PlayerInput : MonoBehaviour<br>{<br>    private PlayerInputActions _input;<br>    private MeshRenderer _render;<br>    <br>    void Start()// Start is called before the first frame update<br>    {<br>        _input = new PlayerInputActions();<br>        _input.PlayerWalk.Enable();<br><br>        _input.PlayerWalk.Color.performed += PlayerColor_performed;<br>        _render = GetComponent&lt;MeshRenderer&gt;();<br>        _input.PlayerWalk.SwitchToDrive.performed += SwitchToDrive_performed;<br>    }<br><br>    private void SwitchToDrive_performed(InputAction.CallbackContext obj)<br>    {<br>        _input.PlayerWalk.Disable();<br>        _input.Drive.Enable();<br>    }<br><br>    private void PlayerColor_performed(InputAction.CallbackContext obj)<br>    {<br>        //change color<br>        if (_render != null)<br>        {<br>            _render.material.color = Random.ColorHSV();<br>        } <br>    }<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        PlayerCalculateMovement();<br>        PlayerRotation();<br>        DriveCalculateMovement();<br>    }<br><br>    private void PlayerCalculateMovement()<br>    {<br>        var _move = _input.PlayerWalk.Walk.ReadValue&lt;Vector2&gt;();<br>        transform.Translate(new Vector3(_move.x, 0, _move.y) * Time.deltaTime * 5f);<br>    }<br><br>    private void PlayerRotation()<br>    {<br>        //Debug.Log($&quot;Axis: {_input.PlayerWalk.Rotation.ReadValue&lt;float&gt;()}&quot;);<br>        float _rotateDirection = _input.PlayerWalk.Rotation.ReadValue&lt;float&gt;();<br>        transform.Rotate(Vector3.down * 1f * _rotateDirection);<br>    }<br><br>    private void DriveCalculateMovement()<br>    {<br>        var _move = _input.Drive.Movement.ReadValue&lt;Vector2&gt;();<br>        transform.Translate(new Vector3(_move.x, 0, _move.y) * Time.deltaTime * 5f);<br>    }<br>}</pre><p>Here switching is carried out by disabling and enabling action maps, this is the main task of this challenge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*ko3HNPDv_Ue-xXL0Yok_cw.png" /></figure><p>Also added drive movement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*DlQLrhU86vjc-xuWLE964A.png" /></figure><h3>Challenge: Bouncing Ball</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zAE2HnHB1cFUOsKCn6IzA.png" /></figure><p>Here are a Floor(plane) and ball(sphere with added Rigidbody) objects. We have to create an input, which allow ball to bounce, if we tap it bounces a little, if we hold it must bounce higher, and as long we hold the button, as higher it must bounce.</p><p>First we create a new InputAction asset with bounce action, in it we add Hold and Tap interactions, set hold time to 1 sec, other settings are by default, save the asset and generate a C# script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*tflFVylVQv6fd_TYIyKyUA.png" /></figure><p>Create a C# script to Ball object, how we perform this action, we will use performed and canceled action, we also add a bool variable to check is full jump performed(is Space key holded 1 sec)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdl6SpFjYr5-2onDQcZa1Q.png" /></figure><p>Here we use AddForce command in Rigidbody component to make it jump.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class BallInput : MonoBehaviour<br>{<br>    private BallInputActions _input;<br>    private bool _fullJumped = false;<br><br>    void Start()// Start is called before the first frame update<br>    {<br>        _input = new BallInputActions();<br>        _input.BallMovements.Enable();<br>        _input.BallMovements.Bounce.performed += Bounce_performed;<br>        _input.BallMovements.Bounce.canceled += Bounce_canceled;<br>    }<br><br>    private void Bounce_canceled(InputAction.CallbackContext context)<br>    {<br>        Debug.Log(&quot;Duration: &quot; + context.duration);<br>        _fullJumped = false;<br>        var _forceEffect = context.duration;<br>        gameObject.GetComponent&lt;Rigidbody&gt;().AddForce(Vector3.up * (10f * (float)_forceEffect), ForceMode.Impulse);<br>    }<br><br>    private void Bounce_performed(InputAction.CallbackContext context)<br>    {<br>        Debug.Log(&quot;Full Jump&quot; + context);<br>        _fullJumped = true;<br>        gameObject.GetComponent&lt;Rigidbody&gt;().AddForce(Vector3.up * 10f, ForceMode.Impulse);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*VznfKs8xnRwgLVjL0zX6Pg.png" /></figure><p>Here is a script, these 2 lines define the force of impulse, Force.Impluse adds an instant force impluse of 1, 10f is a multiplier, and another multiplier is (float)_forceEffect, which defines how higher ball must jump according to how long did player hold the Space button.</p><blockquote>(float) here is a <strong>type cast</strong> — it converts _forceEffect from its current type into a float. context.duration returns a <strong>double</strong>, but Vector3.up * (10f * ...) needs a <strong>float</strong> for multiplication with a Vector3. So you need to convert it to float.</blockquote><p>if we test it, we see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymnqA9HO5I0OlyhwkcP-FQ.png" /></figure><p>It performs a full jump if I tap Space key, which is wrong. Because it is performed even if we tap the Space button</p><p>After several failings I finally found the best completion, here it is:</p><p>First I removed tap interaction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*I8PqRd9sLqJ_9KWMaWCq7Q.png" /></figure><p>Both Hold AND Tap interactions on same binding cause conflicts</p><p>Then corrected the script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class BallInput : MonoBehaviour<br>{<br>    private BallInputActions _input;<br>    private bool _fullJumped = false;<br><br>    void Start()// Start is called before the first frame update<br>    {<br>        _input = new BallInputActions();<br>        _input.BallMovements.Enable();<br>        _input.BallMovements.Bounce.performed += Bounce_performed;<br>        _input.BallMovements.Bounce.canceled += Bounce_canceled;<br>    }<br>    <br>    private void Bounce_canceled(InputAction.CallbackContext context)<br>    {<br>        // fires when key released (whether early or naturally after hold completes)<br>        if (!_fullJumped) //_fullJump == false<br>        {<br>            float _forceEffect = (float)context.duration;<br>            gameObject.GetComponent&lt;Rigidbody&gt;().AddForce(Vector3.up * 8f * _forceEffect, ForceMode.Impulse);<br>            Debug.Log(&quot;Partial Jump, duration: &quot; + _forceEffect);<br>        }<br>        _fullJumped = false; //reset for the next press<br>    }<br><br>    private void Bounce_performed(InputAction.CallbackContext context)<br>    {<br>        //only when button held fpr full 1 sec<br>        _fullJumped = true;<br>        gameObject.GetComponent&lt;Rigidbody&gt;().AddForce(Vector3.up * 8f, ForceMode.Impulse);<br>        Debug.Log(&quot;Full Jump&quot; + context);<br>    }<br>}</pre><p>I tested, it works good, works even if you tap the button, performing a little jump.</p><pre>Quick tap (0.1s)   → canceled fires → _fullJumped false → small partial force ✓<br>Hold 0.5s, release → canceled fires → _fullJumped false → medium partial force ✓<br>Hold full 1s       → performed fires FIRST → _fullJumped = true → full force<br>                   → canceled fires after → _fullJumped true → SKIPS partial force ✓</pre><p>During script correction by mistake I typed _fullJumped = false instead of == symbol, which gave me lot’s of problems, so in future better to keep it in mind or use ! symbol which means ==false.</p><h4>Quick Note on Rapid Prototyping</h4><pre>Keyboard.current.spaceKey.wasPressedThisFrame</pre><p>This is from Unity’s <strong>new Input System</strong> — a direct way to check key presses without needing Input Actions asset.</p><pre>// Old Input System<br>if (Input.GetKeyDown(KeyCode.Space))<br><br>// New Input System (direct polling, no Input Actions asset needed)<br>if (Keyboard.current.spaceKey.wasPressedThisFrame)</pre><pre>Keyboard.current        → reference to the currently active keyboard device<br>.spaceKey                → the specific key (Space)<br>.wasPressedThisFrame     → true only on the EXACT frame the key was pressed</pre><p>Required using statement:</p><pre>using UnityEngine.InputSystem;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*0J4nRPg_RIHNr5doGsBuUA.png" /></figure><h3>UI On-Screen Controls</h3><p>Let’s see how to add UI joystick control movement like in mobile games.</p><p>Here is a documentation</p><p><a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@1.20/manual/introduction-on-screen-controls.html">Introduction to on-screen controls</a></p><blockquote>You can use on-screen controls to simulate Input Devices with UI widgets that the user interacts with on the screen. The most prominent example is the use of stick and button widgets on touchscreens to emulate a joystick or gamepad.</blockquote><p>Let’s create a Player and an UI Image with Knob source image, place it in screen and create an InputActionAsset for it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdtmffPymXznI88ZJyHgZA.png" /></figure><p>Name it and add a component On-screen stick</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*LSYkTx5yVF-ZpCz4YegwVg.png" /></figure><p>Then in eventSystem below you need to add UIInputModule</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*0MsOgJB-5tvyuDCaZ-G2aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*2zZ80KJOwL__KC2fn6YKYg.png" /><figcaption>new UIInputSytem</figcaption></figure><p>Once our joystick is ready we need to constraint it with our player cube. In our new InputActionAsset we add a movement action with value of Vector2D as our OnscreenStick requires 2D Vector control. Also we add stick binding for it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*JY5DcVz3I-SlIUWVBGR1Yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*lgssA3Gbs1u3QSnC1ve2Dw.png" /></figure><p>Save it and generate a C#script. Then we create a PlayerJoystick script.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class PlayerJoystick : MonoBehaviour<br>{<br>    private JoystickInputActions _input;<br><br>    <br>    // Start is called before the first frame update<br>    void Start()<br>    {<br>        _input = new JoystickInputActions();<br>        _input.PlayerJoystick.Enable();<br>    }<br><br>    // Update is called once per frame<br>    void Update()<br>    {<br>        Vector2 _direction = _input.PlayerJoystick.Movement.ReadValue&lt;Vector2&gt;();<br>        transform.Translate(new Vector3(_direction.x, 0, _direction.y) * Time.deltaTime * 5f);<br>    }<br>}</pre><p>set the control path in OnScreenStick</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*gukrRGSYpsKYXBlylZTJ1w.png" /></figure><p>attach OlayerJoystick to Player object and test it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liwDf3hTORuNqwsZ7trq0Q.png" /></figure><p>Now I can move it by UI element</p><h3>Challenge: Progress Bar Charge</h3><p>Create the ability to hold down the space key to charge up a progress bar. When you release the space key the progress bar goes down.</p><p>Let’s create a new scene for this challenge, first we add a Slider UI element</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKtzNaVLKTItttwc4IpXig.png" /></figure><p>we can delete the Handle, we don’t need it. In fill area we increase the padding 15 to 5. then we see in Value 1 it fills full bar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*yLAW2NnSd5jEIE4UuKJ75w.png" /></figure><p>In here we create a new InputAction simple button action input with Space key binding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*dpLkgYlK_NZUQLMOlB-niA.png" /></figure><p>We don’t need hold or press interactions, we can use start and cancel action commands instead. Don’t forget to saveAsset and generate a C# class.</p><p>We create script UIChargeBar and attach it to Slider</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*FM6BOlaYsjl4Fq-q6NgUcw.png" /></figure><p>This is how we initialize and register input action as before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*U0jGu4EAe_ujCknhBDrilw.png" /></figure><p>Next we need to access UI library to change the slider value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*tQZVVsa2zP8bA0SprznrTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*IyXEH5SEjGekF83pUK5icw.png" /></figure><p>and attach it in inspector</p><p>Here we use Coroutines to charging, because filling the value happens by time while we are holding the button. Also we need a bool check for charging and recharging.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class UIChargeBar : MonoBehaviour<br>{<br>    private UIInputActions _input;<br>    [SerializeField] private Slider _slider;<br>    private bool _isCharging = false;<br><br>    void Start()// Start is called before the first frame update<br>    {<br>        _input = new UIInputActions();<br>        _input.UI.Enable();<br>        _input.UI.ChargeBar.started += ChargeBar_started;<br>        _input.UI.ChargeBar.canceled += ChargeBar_canceled;<br>    }<br>  <br>    private void ChargeBar_started(UnityEngine.InputSystem.InputAction.CallbackContext obj)<br>    {<br>        //start charging<br>        _isCharging = true;<br>        StartCoroutine(ChargingBarRoutine());<br>        Debug.Log(&quot;Charging...&quot;);<br>    }<br><br>    private void ChargeBar_canceled(UnityEngine.InputSystem.InputAction.CallbackContext obj)<br>    {<br>        //done charging, start recharging<br>        _isCharging = false;<br>        Debug.Log(&quot;Charging completed!&quot;);<br>    }<br><br>    IEnumerator ChargingBarRoutine()<br>    {<br>        while (_isCharging)<br>        {<br>            _slider.value += 0.2f * Time.deltaTime;<br>            yield return null;<br>        }<br><br>        while(_slider.value &gt; 0 &amp;&amp; !_isCharging)<br>        {<br>            _slider.value -= 0.1f * Time.deltaTime;<br>            yield return null;<br>        }<br>    }<br>}</pre><p>It fills for about 1 sec here. We can control charging time by simple mathematic modifying. Let’s say we want to take it 5x more time to charge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*XHOTpQ4tf-K6DzP7rghENg.png" /></figure><p>This multiplier defines the speed of charging and recharging, maybe we can do recharging more slower. So the main logic is correct you can customize it as you want.</p><h3>Practical Uses</h3><p>Let’s see how to implement Input System Actions in real games, best practices, clean designed structure. We see it in example of setting up the basics like player movement, shooting with cooldown system and ammo count. There are many other ways, structures. There is no wrong ways, all ways bring us to the correct result, but some of them are more optimized, flexible and easy editable. As software engineer we always must to find the best way.</p><p>Quick brief about the way we do it. We create an Input Action Asset for the whole game, in it we add an action map for the Player which might have lot’s of actions. In our case we add movement, fire. This InputActionAsset might have other Action maps such as Drive, Fly, UI, etc. Then we create 2 C# scripts: PlayerManager and Player(Behaviour). 1st is only for Input implementation, we organize a communication between these 2 scripts and 2nd script will contain only those commands which define it’s behaviour. In my opinion this is a safe clean and flexible approach. So let’s start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__hB26vx_o9Vo3uzFPiNGA.png" /></figure><p>This is the structure. Here PlayerManager class is attached to PlayerManager empty GameObject and Player class is attached to Player object(cube in our scene). I also set up the GameInput with it’s actions, which we need in current time. Player manager is responsible for Input initialising and registrations, Player is for behaviour.</p><p>Let’s see how to manage inside of each scripts. First we set up the movement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSQ8gqaUoImiTMi2FE5giw.png" /><figcaption>PlayerManager class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vRNRMqZjoij4CQiSMhd0g.png" /><figcaption>Player class</figcaption></figure><p>Don’t forget attach required references(Player) in inspector. Next we will set the Fire with cooldown(delay) function. I tried to implement delay within action interaction options. But, it didn’t work. So, I’ll do it with old way(with code). Let’s first add some projectile prefab(capsule) to shoot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMdoK997fa7B2kVjTpHMnw.png" /></figure><p>In PlayerManager I registrated the Shoot action performance, it will call _player.Fire() method to when shoot is performed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c3itfEZY_qeV0popdpzyQ.png" /></figure><p>Now let’s add a projectile behaviour, it only must move up and destroy itself when exits the screen space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Slqz7p7WW0gRjwx0YbELPg.png" /></figure><p>Now we need to add an ammo count</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6ie-FG9dzZE3XiL5vkOmg.png" /></figure><p>That’s is, I recommend you to go with this approach, make your workflow clean, modular, reeditable. If you type all initialization and behaviour in one C# class it easily gets very mess and very long script, making hard to fine bugs and other actions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ae3efc5b1ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cinemachine framework]]></title>
            <link>https://medium.com/@yanvar103/cinemachine-framework-17af16e4d165?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/17af16e4d165</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 15:22:19 GMT</pubDate>
            <atom:updated>2026-08-01T15:22:19.197Z</atom:updated>
            <content:encoded><![CDATA[<p>Task:</p><p>You are assigned to create a camera system for a space simulator. You will need to use Cinemachine to set the virtual cameras in the correct place. You will need a cockpit camera and a 3rd person behind-the-ship follow camera. Finally, you will need to create a cinematic camera that will play a sequence of camera shots can astound players if they have not interacted with their controller within 5 seconds.</p><ul><li>Add the environment to your Unity Project</li><li>Choose a spaceship out of all of the spacecraft available in filebase.</li><li>Choose your music — you should pick something from freesound.org</li><li>Add in post processing to highlight engine emissions and lights, color correction, ambient occlusion, and bloom.</li><li>Add Reflection Probes/light probes</li><li>Add flames from engine (prefab)</li><li>Add space particle dust (prefab)</li><li>Look on filebase and add a cockpit.</li><li>Add it to your ship</li><li>Add a in-cockpit POV camera</li><li>Add 3rd person follow camera from behind the ship</li><li>When you press ‘R’, be able to swap between the internal camera and the external camera</li><li>Add a minimum of 5 additional camera shots during a cinematic sequence.</li><li>There should be at least:</li><li>1 camera with a unique post processing stack,</li><li>1 camera that animates on it’s own, one camera that has shake,</li><li>and 1 camera that uses an extension.</li><li>When the player hasn’t moved the mouse or pressed a key within 5 seconds, have the cinematic camera engage.</li><li>When the player presses any button or moves the mouse, the camera should go back to the original view</li><li>Show the user how to properly navigate between the different cameras</li><li>Add a game manager with quit app ability</li></ul><p>First is Environment. As I was using one project to all this Cinemachine and Timeline course and created only a new scene for this framework in the same project, which uses standart built in Unity render. I’m adjusting the outcome from this. First is a skybox, I attached it from given files skybox material</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*WayfaRtXbQiH-GmjUvEkaQ.png" /></figure><p>Imported a spaceship 3d model, added it under empty SpaceShip gameobject, also added there flame particle systems, engine models with emission parts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xs_1i9ewPIUpwzPPZVM05Q.png" /></figure><p>light cubes and one spot light with same color as flame</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*1WHRELrqrYeeIGIMuTy9Qg.png" /></figure><p>Problem was in flames, many times I tried to rotate it, but didn’t work, finally I found the solution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*mVEYtwu7iAMl9jJkwnfOiA.png" /></figure><p>in inspector of it’s particle system check this option, then you can manipulate it in scene. I even tried to rotate textures before I found it.</p><p>I added a background music, gameObject with attached to it audisource with audioclip, check play on awake, loop</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*rbScHPUHTeze0oD0tYxwJw.png" /></figure><p>Then I added Post proccessing, it’s little bit different in standart render, first you have to create an empty object name it Post Process Volume, add to it Post process Volume component, check is Global, create to it new profile. Then add a new layer post process volume, set this gameObject’s layer. In main camera add Post process layer component, set the layer, set anti aliasing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*7GWOsxu2MQ475QRbFV1UXg.png" /></figure><p>Then you can add your favourite effects in your profile.</p><p>Also added reflection probe and light probe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*igYYKPc2wMdcChLgDF_BRA.png" /><figcaption>light probe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*pdn9or5wawX0eO46BIfCig.png" /><figcaption>reflection probe</figcaption></figure><p>Created a space particle dust with cone shape</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvdMpINL1R1j7-0hFB1vDw.png" /></figure><p>with these options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*yNTUpzkm1x8JJaX2TBfvoQ.png" /></figure><p>added imported cabin model here inside the spaceship model approximately in cabin place</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlHPFlejB_jh2O-qxKnqkw.png" /></figure><p>If I disable the spaceship you can see it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*GB9vdx-n3KI76P74lqp4aQ.png" /></figure><p>Next is maintain all Vcams, first is cabin camera</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*2rJk_h_5VgAfzvb-UuGkqg.png" /></figure><p>carefully adjust these settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*UjWSVOyGdRhgLEpgXYFEAg.png" /></figure><p>exterior camera(3rd person)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*8UbRFnSm7-6rOc3UHBbl3A.png" /></figure><p>And blend list camera for cinematic sequence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*d-ArNTzl9DaYj0R-F5L2WA.png" /></figure><p>Here we have some shaking cams in which I added noise</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*72sps29IXB1KjPs6U1R65Q.png" /></figure><p>One of them has it’s own post processing stack extension to imitate the security ship camera</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*TJ03FSfOEoNJMhOywx2-Mg.png" /></figure><p>Next thing is a Camera manager, which holds te script according to the task:</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using Cinemachine;<br><br>public class CinemachineFramework_VCamManager : MonoBehaviour<br>{<br>    [SerializeField] private CinemachineVirtualCamera _vCamCabin;<br>    [SerializeField] private CinemachineVirtualCamera _vCamOut;<br>    [SerializeField] private CinemachineBlendListCamera _blendListCam;<br><br>    private int _activePriority = 15;<br>    private int _defaultPriority = 10;<br>    private bool _vCamCabinOn = true;<br>    [SerializeField] private float _idleTimeThreshold;<br>    private float _idleTimer = 0f;<br>    private bool _cinematicOn = false;<br><br>    private void Start()<br>    {<br>        _vCamCabin.Priority = _activePriority;<br>        _vCamOut.Priority = _defaultPriority;<br>    }<br><br>    void Update()// Update is called once per frame<br>    {<br>        if (Input.GetKeyDown(KeyCode.R))<br>        {<br>            if (_vCamCabinOn)<br>            {<br>                _vCamCabinOn = false;<br>                _vCamCabin.Priority = _defaultPriority;<br>                _vCamOut.Priority = _activePriority;<br>            }<br>            else<br>            {<br>                _vCamCabinOn = true;<br>                _vCamCabin.Priority = _activePriority;<br>                _vCamOut.Priority = _defaultPriority;<br>            }<br>        }<br><br>        if (InputDetected())<br>        {<br>            _idleTimer = 0f;<br>            if (_cinematicOn)<br>            {<br>                _cinematicOn = false;<br>                _blendListCam.Priority = _defaultPriority;<br>                _vCamCabin.Priority = _activePriority;<br>                _vCamOut.Priority = _defaultPriority;<br>            }<br>        }<br>        else<br>        {<br>            _idleTimer += Time.deltaTime;<br>            if(_idleTimer &gt;= _idleTimeThreshold &amp;&amp; !_cinematicOn)<br>            {<br>                _cinematicOn = true;<br>                _vCamCabin.Priority = _defaultPriority;<br>                _vCamOut.Priority = _defaultPriority;<br>                _blendListCam.Priority = _activePriority;<br>            }<br><br>        }<br>    }<br><br>    bool InputDetected()<br>    {<br>        return Input.anyKeyDown ||<br>            Input.GetAxis(&quot;Mouse X&quot;) != 0 ||<br>            Input.GetAxis(&quot;Mouse Y&quot;) != 0;<br>    }<br>}</pre><p>And a game manager script attached to an emty gameobject GameManager</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class GameManager : MonoBehaviour<br>{<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        if(Input.GetKeyDown(KeyCode.Escape))<br>        {<br>            Application.Quit();<br>        }<br>    }<br>}</pre><p>It gives us quit app ability</p><p>Added an UI Text mesh pro element with these settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijocs2FLDoVDdT6nw5WSQg.png" /></figure><p>As addition to all these tasks I added a 3D sound to Engine object, adjusted parametres and it’s sphere radius</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cfvl5Qcq8taHGtOLSxjgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*LRjPLHZDjmeyLkBfaD2DoA.png" /></figure><p>During Cinematic sequence when camera is close to engine you can hear loud engine sound.</p><p>I think that’s all, quick brief explanation, because all these things we already passed before.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17af16e4d165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Timeline and Cinemachine part-2(Timeline)]]></title>
            <link>https://medium.com/@yanvar103/timeline-and-cinemachine-part-2-timeline-17a619d08981?source=rss-e9430a9fc615------2</link>
            <guid isPermaLink="false">https://medium.com/p/17a619d08981</guid>
            <dc:creator><![CDATA[Anvarjon Yuldashev]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 11:04:01 GMT</pubDate>
            <atom:updated>2026-07-30T11:20:49.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s remember a timeline from previus part:</p><p><strong>Timeline</strong> — cinematic sequencer:</p><ul><li>Animate anything over time like a video editor</li><li>Control Cinemachine cameras, animations, audio, particles all together</li><li>Perfect for cutscenes, intros, scripted events</li></ul><p>It’s kind a improved version of animator. Now open up a timeline window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*UKlBf3YhtWUNHu1WGpwKbw.png" /></figure><p>Create an empty object and name it Timeline, select it then create a timeline for it in special Director folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBabP05toHqDsaag6WUr6w.png" /></figure><p>You can see here also <strong>Playable Director. It </strong>is a component that <strong>plays</strong> a Timeline — it’s the “player” for your Timeline asset, similar to how a video player plays a video file. GameObject → Timeline asset created → Playable Director component automatically added. Timeline Asset = the “recording” (stores all tracks/clips). Playable Director = the “player” (plays the recording on a specific GameObject). It has some parametres:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*F9SiFQzvF0_cqLwdpBDd3Q.png" /></figure><p>Wrap Mode — What happens after Timeline ends</p><pre>Hold → freezes on last frame<br>Loop → restarts from beginning<br>None → stops completely</pre><p>Update Method — How time is calculated</p><pre>DSP Clock → audio-synced, most accurate for music<br>Game Time → normal Time.deltaTime, affected by Time.timeScale<br>Unscaled Game Time → ignores pause (Time.timeScale = 0)<br>Manual → you control time yourself via script</pre><p>Playable - Which Timeline asset to play. Play On Awake — Auto-plays when scene starts. Initial time — how long it waits after scene starts.</p><p>In timeline window we have here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lsc4D3gzBURfJ08G7oBdwQ.png" /></figure><p>option button in which we can set frame rate, change the scale to seconds or frames or timecodes etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRCHQ0Hncdd0ndkuSpFF7Q.png" /></figure><p>Here we can add individual track inside the timeline.</p><h3>Timeline Animations</h3><p>Now let’s add an animation into the timeline and see what can we do with it. First we create some objects(plane and cube).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7byEBNNi-XJ35N6iNHR4eg.png" /></figure><p>If we drag our cube to Timeline window we see these options, for this kind of object better to chose Animation task. It auto creates an animator in cube object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4P9vVFfwQmZIhPiBdZIFg.png" /></figure><p>Let’s make some animation here, press record button and add keys to position of cube</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXMYgs4g2L31ZVSsbDjlrg.png" /></figure><p>So we got some animation, if we double click to it we get to animator window. We can modify the animation in animator window as earlier.</p><p>In animator it says that this animation is linked to Timeline editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1u4gDVolFdwsfs7a8TXHZQ.png" /></figure><p>In Timeline window we can convert this animation to clip track by clicking RMB on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dagp_0PXPq_8-G0jxURaBw.png" /></figure><p>Now we can scale the it’s duration or move this clip through the timeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APuzU1YgGUtfIl_8WqG6lg.png" /></figure><p>In inspector we can do a lot of modification with this clip, set the speedMultiplier, Ease in/out, start/end etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0fmrAfwLudNG4hst2N6_g.png" /></figure><p>By holding ctrl button you can set ease in/out duration by dragging in Timeline window which is very comfortable than in inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*IA8XmJvqvAGuHKMnvWrZiw.png" /></figure><p>You modify this as a clip and it doesn’t spoil the original animation. These manipulations are very usefull while stitching lot’s of animation clips together.</p><p>If we press ctrl+s to save, the animation will store under the timeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSqKw1s7vZ5QpcinwUN8mg.png" /></figure><p>We can add more animations to this same object(cube). Let’s add some vertical movement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9w2mSRqxTCFL4vJsBcxQFQ.png" /></figure><p>If we save it is saves under the timline asset in project folder, if we delete it in timeline it also deletes from project folder. You also can place these animation as you want also blend them like this, very flexible and comfortable system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*MYLuLP_Rf9jobaNB-kUjtg.png" /></figure><p>In real games your player can have multiple animation like standing, walking, smoking, talking etc. Them have to be blended in different cases.</p><h3>Timeline Controls</h3><p>This is a mix mode, in which one animation can blend with another if you move it to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-yfHKssINCzv7UGAavnfQ.png" /></figure><p>In ripple mode if you move one animation it pushes others keeping the origin distance between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TOX7Pq11K6fNIFmBRoTnQ.png" /></figure><p>In replace mode if you move one animation to next one, it is going to replace the next one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bc9PWyO463k0t740fktfJg.png" /></figure><p>Here we can have multiple timelines, but about this we will talk later</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fy-_iLG42gOjuHzlBtY8nA.png" /></figure><p>If you pless A button in timeline it frames all elements in it, helps you with navigation when you need to the whole timeline. To work with certain clip, select it and press F to frame it. If you select some clips and click on Tile they will place right after each other without gaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*htVYr7PA9MVgGfE5cQqq2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*rv2WCgxjIILp7r80_QtsCA.png" /></figure><p>you can get the visibility of axis graphs of animations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRmGKr10pe5ZkjD1nW154w.png" /></figure><p>You can split the clip by clicking S button in place where the marker is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3xG7CdO--V6mdv4ghiMng.png" /></figure><h3>Pre and Post Extrapolation in Timeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*aiew78pQ2VWHxMyqBQksdw.png" /></figure><p>Extrapolations define what to do in empty spaces between animations, before animation is pre-extrapolate, after animation post-extrapolate. By default all Extrapolations are set to Hold. Hold means if it pre il holds the starting position before animation, let’s for example set post extrapolation to ping pong, after animation in gap between the next animation it runs the reverse animation. In timeline you can see them before and after the clip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*wlCOy4NlTub6MV3Ju6qdhQ.png" /></figure><p>None — snaps back to the beginning position, If you shrink the animation and set post extrapolate to continue it will continue the animation and hold the last position. And also loop — which will loop the clip.</p><p>If we have 2 animations and the end position of 1st clip dismatches with beginning of the 2nd clip. We will get jump cut to next clip, but sometimes we want to continue 2nd animation from ending the 1st animation with seamless transition. How we do it. We can select the 2nd animation and RMB on it select match offsets to previous Clip</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*fVOMeKdWnuDh0nxo20ewqg.png" /></figure><p>or select the 1st clip and choose match offsets to next Clip</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*2I9-Igrxi9DLqCOHfLIVPQ.png" /></figure><p>These commands add offsets here for 2nd clip</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*pgWvFgbA8OAUd5Mm6Pq7fA.png" /></figure><p>We can get seamless transition also with blending 2 animations adding ease in/out durations as before.</p><h3>Repositioning Timeline animations</h3><p>If you want to animate using timeline best practise is to have a parent object over it, then you can move it using parent object, change the position rotation of whole animation, you will have more flexibility. This kind of structure is the best:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STsXunPmCCBSc8rQ7tL1Lw.png" /></figure><p>Here Director is an empty obj with 0 transform, Cube_parent is also empty with 0 transform, selecting cube we create a timeline on it. We drag cube into this timeline, add animation track, do some animations. Then we can move those animations with cube_parent, switch on/off them using director. Always have a parent over the animated game object.</p><h3>Track Types in Timeline</h3><h3>Activation track</h3><p>Activation track is literally activates/deactivates gameObjects in timeline. I can drag objects into timeline with activation track option or create an activation track pressing + button and attack objects you want</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mrjruGA3dLJ269hC7qliw.png" /></figure><p>For example here sphere object appears at the end of cube recorded animation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFNHrRxR8i8kg3zDPVRWFQ.png" /></figure><p>Sphere is active only in this active zone. With this, for example, you can manage flickering lights without any code.</p><h3>Audio Track</h3><p>It’s a track which in timeline plays audio files with similar parametres as animation track. You can just drag them from project folder into timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-kbfx9X4Ws9H_D8pn9H8A.png" /></figure><p>You can set ease in/out, play speed, add loop, split at mark place by pressing key S.</p><p>You also can add multiple audio tracks, aslo multiple activation track for other objects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRdUeoBUBLuOAJV-mKtDnQ.png" /></figure><p>You can add to them audioSource, create an empty object, you can name it as audioSource, then drag it to audio track, it will ask you to add audioSource component, we will add it. By this we can set 3D sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aczDmRWlRjAm9fvNKZdWHw.png" /></figure><p>In audioSource settings we set spatial blend to 1 to make it as 3D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*yd46oYpsyQZBnneB0j0n4A.png" /></figure><p>In scene view we can set the radius sphere of this AudioSource</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*er2VDWCKjJkPViBPrGZfhg.png" /></figure><p>As bigger this radius is and as closer this sphere is to MainCamera as louder will be our audio. This 3D audio effect is always needed in game, it makes sense that closer objects are more heareble. You can explore other audioSource options from inspector on your own.</p><h3>Control Track</h3><p>This type of track is used when we have multiple timelines in one scene. It controls timelines, I’ll show you how it works in example to better understand it. We already have CubeTimeline, let’s create another one with new Capsule object and add any Capsule movement animation in it adn save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpNYXHwP3ceWFOG_LdSBPA.png" /></figure><p>Let’s add in one of them Control track, for example, in CubeTimeline, then drag our object with timeline(which is Capsule) into Control track space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsE49Y7rsAzke2ABfLGH5Q.png" /></figure><p>So here we control whole CapsuleTimeline in CubeTimeline. We also have some parametres to control</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*-slXDUtZ3gYVKEL62FkoEQ.png" /></figure><p>I also can copy/paste them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*Oi8Hz1hTwKDnmN7LRo7-ww.png" /></figure><p>In playMode CapsuleTimeline starts at that moment where we placed it in CubeTimeline, here our CubeTimeline will be the main timeline that controls other.</p><h3>Challenge</h3><ul><li>Create a sphere that collides into the box.</li><li>When it hits the box, it plays a sound and initializes particles.</li><li>Must use all 4 tracks — an animation, audio, control, and activation.</li></ul><p>So let’s create a scene with cube, plane and sphere. Also we need a particle system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*jjCIdK3SHn-IyMQSbLz9og.png" /></figure><p>We place it under the cube</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcscHfU6IE7n4SN2Mk2-Ww.png" /></figure><p>Once the scene is ready let’s manage timelines. We need here 2 timelines, main timeline will be under the sphere(animation track, control track). It will controll the second one, which is under the cube(audio track, particle activation). By rule we don’t forget to add parents on timeline holding objects and all these parents must have 0 transforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jj-PRA5S0MipEU7F0pHX8Q.png" /></figure><p>Timelines are created, let’s add all needed tracks, in CubeTimeline they start after some gap(2–4 frames), no need to add audioSource if you don’t need 3D sound effect, you can just drag an audiofile from project folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkzFjK4qCj8fJXHyduu-vg.png" /></figure><p>In sphere timeline I add sphere animation, then a control track and director of cube into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XJlePP4uuMKmBoKhWh9wg.png" /></figure><p>As you noticed before this moment Cube also is deactivated, but we want it to be shown, during sphere animation. For this we need to check off Control Activation on it and check Control children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpwSsnT1m31QxZ6y5bqMWQ.png" /></figure><p>Also don’t forget to check in particle system this option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*r7Iv5TwxNSphx0dztTeWEg.png" /></figure><p>So in my scene it works, and all this actions without any code, with very simple steps.</p><h3>Challenge — Exploding Lightbulb</h3><ul><li>Make a light bulb blow out using timeline.</li><li>Create the light bulb — grab from Filebase and add a point light/shadow.</li><li>In timeline, have the bulb flicker for 1/2 a second and turn off</li><li>Add SFX to the bulb popping at the appropriate time.</li><li>Have the light build sway a little after hit.</li><li>Make the entire sequence play when pressing the “K” button.</li></ul><p>First we prepare the scene, created a new scene added all needed objects</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQaTStARj8XtS49Irn0LVg.png" /></figure><p>Here I also added new skybox material and attached it to Lighting Settings/Environment/SkyboxMaterial to make environment darker. Downloaded Ceiling_Bulb model, added under it a PointLight with shadow on option. Cube is here just for show the shadow. As you noticed here are 3 Ceiling_Bulb models: 1st is active before the Timeline start, 2nd is for flickering in Timeline(which is under the Director), 3rd also under the director is for switched off Ceiling_Bulb after flickering. It has no Point light under it and it has another material which emission is turned off. Timeline we add to Light_parent object, because Ceiling_Bulb is a prefab, Light_parent has it’s parent too, so it’s ok. Let’s manage the Timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSkYhG-DsnPD_DfEkMeCPg.png" /></figure><p>This is how it must be, look at this, we have some delay at start before flickering(before start lamp) is active 0.30 sec. Then the flickering moment. on and of lamps swapping in every 0.05sec 5 times, then only off is active, also I imported the sound effect which is activating somewhere in flickering moment(sound is slower than the light speed) and off lamp starts to swing little bit about 3 sec.</p><p>At start Ceiling_Bulb_BeforeStart is active and Director is deactive, when we press K button Director must activate start the timeline(also timeline will deactivate Ceiling_Bulb_BeforeStart). We do it with script, which will be attached to a new separete object, we call it Trigger. Very simple script</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class LightBulb_blowing : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _director;<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        if (Input.GetKeyDown(KeyCode.K)) _director.SetActive(true);<br>    }<br>}</pre><p>That’s all, don’t forget attach the Director in inspector.</p><h3>Using Timeline to Create Explosions</h3><p>Imagine that the Air plane is flying at some speed, and you have to activate it’s explosion and disappearing, we already done it’s 2D version in space shooter game with script. How we can do it using timeline?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3tQKk1b_yhFPtZyUbJk1Q.png" /></figure><p>Here is how we can do it, there is a structure Empty Plane_position object which contains the script, script will move the Plane_position and all objects under it.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br><br>public class AirPlaneMovement : MonoBehaviour<br>{<br>    [SerializeField] private float _speed;<br>    [SerializeField] private GameObject _director;<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        transform.Translate(Vector3.right * _speed * Time.deltaTime);<br>        if (Input.GetKeyDown(KeyCode.K)) _director.SetActive(true);<br>    }<br>}</pre><p>We have director_postion empty parent object to corrective the position and director under it which has a timeline, this object will be attached to script and K button activates it in GameMode. And we have an downloaded ready explosion prefab, copied 3 times to make explosion sequence before disappearing. And downloaded air plane 3d model is under Director_position. If you see the timeline, it activates all exlosion and before the last explosion airplane model deactivates. Director must be inactive at start. Very simple way and fast to this task. You can modify it by adding some destructions etc.</p><h3>Signal Track</h3><p>Signal track are usefull when in timeline you have to call a method(function) from certain script in certain frame or second. For this in timeline you add a Signal track attach the object which contains the script as reciever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pfa3BU-Kp7raKRzhM3KsGA.png" /></figure><p>Then add a signal emitter where you want</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*1oaPQn3Eqw43FyAaL-V_9Q.png" /></figure><p>Select the emitter, in inspector create a signal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*9VXAo3biQDEgR9R46shtAw.png" /></figure><p>Let’s add a simple method to our cube object script, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*7YPcmqUqvqTiX6h6DDbjrg.png" /></figure><p>it must be a public. Then in inspector if you select cube or emitter you can set the function, it pulls the method from script which is pulled from recieve object(cube)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*h7W52EcgublucGbfj2rhOA.png" /></figure><p>You can do it without adding Signal track by adding Signal emitter on Activation track</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-JUdI3iF5fo9yXgDAd9Lg.png" /></figure><p>After this you have to define cube as a reciever.</p><h3>Signal Emitter to Alter Timeline Playback</h3><p>We can control timeline playback using signal emitters with script functions, for example, pause, play, skip some seconds, set back to some seconds at certain moment etc. I’ll show you how it works. We already have a director with timeline. Let’s add a script and add it to this director as a component. We will type here some functions and for this we need to access to timeline commands library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*5y8N7WoYRu6epm6FZ9tQHw.png" /></figure><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.Playables;<br><br>public class PlaybackControl : MonoBehaviour<br>{<br>    [SerializeField] private PlayableDirector _director;<br>    [SerializeField] private float _startPoint;<br>    <br>    void Start()// Start is called before the first frame update<br>    {<br>        _director = GetComponent&lt;PlayableDirector&gt;();<br>    }<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        if (Input.GetKeyDown(KeyCode.P)) PlayTimeline();<br>    }<br><br>    public void PauseTimeline()<br>    {<br>        _director.Pause(); //pauses the timeline<br>    }<br><br>    public void PlayTimeline()<br>    {<br>        _director.time = _startPoint; //sets the time to _startPoint(seconds)<br>        _director.Play(); //plays the timeline from  _startPoint<br>    }<br><br><br>}</pre><p>Here you can see PauseTimeline, PlayTimeline I added, very simple, let’s try to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-1kHwAuvsfFSsyty-p_Zw.png" /></figure><p>Here let’s say I want Timeline to be paused at 2 seconds, so I add here new Signal emitter, created new Signal_pause, set reciever to Director, select the function. I tested, it actually works. Let’s add another one function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*S8FacDXMMk0Hq6s3S7_tjA.png" /></figure><p>set it in Signal emitter inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*h-LcAujvAc6z9bP1MgZ0tw.png" /></figure><p>It loops the timeline beteew about 9 and 6sec. Then we need another function that can exit the loop etc. This kind of manipulations you can do with Timeline playback using signal emitters.</p><h3>Challenge: Load Level Through Timeline</h3><ul><li>Create a load level cutscene. Create 2 separate scenes.</li><li>Create a timeline that plays. After 4 seconds, it initializes a signal that advances it to a new scene.</li><li>Play the timeline on start and have it load the new level.</li></ul><p>So let’s make the cutscene is to be loaded when we press E button. In cut scene we just run the timeline for example 5 sec(imagine something happen in this time), then we place a signal emitter to this point(5sec) which activates in script LoadNextLevel() function. Let’s create a new gameObject that holds this script, name it as Player, and another GameObject that holds the timeline — Director. Also we create a new scene or we can use one of the existing scenes, let’s use lightBulb challenge scene.</p><p>We already know how to manage connections in timeline and inspector, so I will show you only the script. I called it SceneAdvance, first we need a new library to access the SceneManagement commands.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.SceneManagement;<br><br>public class SceneAdvance : MonoBehaviour<br>{<br>    [SerializeField] private GameObject _director;<br>    <br>    void Update()// Update is called once per frame<br>    {<br>        if (Input.GetKeyDown(KeyCode.E) &amp;&amp; _director != null) _director.SetActive(true);<br>    }<br><br>    public void LoadNextLevel()<br>    {<br>        SceneManager.LoadScene(&quot;Timeline_2ndChallenge(lightbulb)&quot;);<br>    }<br>}</pre><p>But before we need to add these 2 scenes into ScenesInBuild(Build Settings window)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*5zynqKUsa-ndnfzh9l5VmA.png" /></figure><h3>Character Cinematics and Timeline</h3><h3>Characters Animations in Timeline</h3><p>Here we practice some character animations and transitions between them in Timeline. Let’s download some animations from mixamo. Pay attention to one option while downloading in mixamo. If you are downloading for example walking, running or other kind of animation that allows to change position better tick off In Place option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*eu1qG-TAEoHnCtoDawhYMQ.png" /></figure><p>Make all animations Humanoid. Then create a timeline and place Player under it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Jfz7HZFyJBBwontlI6VEQ.png" /></figure><p>Drag Player to timeline as animation track</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*392BBBjtZXyYid-5JnSD8A.png" /></figure><p>Then drag animations into it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JK4sE3QX-5gBToswYczLA.png" /></figure><p>If you want to loop animation in Holding part turn the loop otion on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRIJeUM4EnOqVv3qqJs6Fw.png" /></figure><p>After Entry anim we add dancing anim with smooth transition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWgrtnvglXMqCh6fGZhyqQ.png" /></figure><p>here we face an issue, intransition point the position of player is here. but dancing animation plays in 0 position(we get position dismatch).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJk5o_6JEL6k4oAXSRuV9A.png" /></figure><p>To avoid this we have a Match offsets to previous clip command that adds an offset, in our case to dance anim option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*Z1UU_A6KXhcJSCw_-fCa4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXABntDwIvFoj_OD89A3Ww.png" /></figure><p>Now he starts dancing at that point where he the Entry anim ends.</p><h3>Character Override Animation</h3><p>Often there is a need to add an animation on top of another animation, for example, do something with hands while walking, punch or hand gestures while walking, override only part of skeleton(hand) animation on walking anim. For these cases we have avatar mask</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*4cHlJ7gAuPyBrXHZfiIHnw.png" /></figure><p>We also need to add an override animation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMZD0m0iSFft_SN74hpLhQ.png" /></figure><p>Let’s say we want to add Entry hand animation over walk anim</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BL8fep3misDuAnzPLZM8zQ.png" /></figure><p>We create an avatar mask, in it in Huanoid settings we disable un needed skeleton parts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Q_8fvURH8rXtMCvFxFRXaA.png" /></figure><p>Then select the override and in inspector define this avatar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*027uAy0deRWeqWuCQRS9iw.png" /></figure><p>Also you can add easy in/out, so you get nice resoult without painstaking manual adjusting.</p><p>What if you have an animation only in Place mode and you have to move it manually. We can’t record this type of character animation, but we can add a new animation track by dragging player into timeline and start record it in this track with adjusting the speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPWEGt91Xj-CsFsKoxepHA.png" /></figure><h3>Challenge: Winning the Race</h3><ul><li>Create an animation of a character running</li><li>When he is at the end point, have another timeline create a particle burst signing the finale</li><li>When he hits the end of his run, have him lift his hand in the air in victory, then limp his way out of the scene.</li><li>All of this is done using timeline. Animations are provided.</li></ul><p>First I created a box which is a finish line, added the player, created a new timeline, player animation track in it, added FastRun into it with loop and some position offset. Here in timeline 1.15 sec he crosses the finishline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*u6yVnm1HlCPO_acSoq0bag.png" /></figure><p>We add an override animation track and create an avatar mask to add victory animation over FastRun</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeyVvpuh2Zn5vNMPIJPXSA.png" /></figure><p>Here is the final RaceTimeline for character</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlK-6UQKMBcbkTFnXrEwAA.png" /></figure><p>Time to add particle burst. Create an particle system with these options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*YQljVIHG858ejiu_zgDZDQ.png" /></figure><p>you can dublicate it. place them to finish line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQcDVoYU3enc_PPWvIobJA.png" /></figure><p>Add them under ParticleTimeline as a child, also into it as activation track</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reXKRdXRDcClinVoR42Cqg.png" /></figure><p>Then add this timeline into RaceTimeline into control track at finish point</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GMpp1ey1k9ZPYBVFg2fSg.png" /></figure><p>you can check it in gamemode.</p><h3>Create a Cinematic Event Using Timeline and Triggers</h3><p>In here I do an animation of the preparation and takeoff of a spaceship in timeline, turn off play on awake option, then add a trigger(cube or some another game object) add a script to it with OnTriggerEnter (if other is Player) access to Timeline(PlayableDirector) and run Play() in it as we did before.</p><h3>Challenge: Treasure Chest System</h3><ul><li>Download a treasure chest from filebase and open it via Timeline.</li><li>Create a timeline animation of the chest opening up with particle explosion and sound effect.</li><li>Instantiate a treasure after opening</li><li>Create a trigger that opens when the player walks into it.</li></ul><p>After importing the chest model into the scene, check the pivot of it’s cover, it must be in pivot, so if you rotate in x axis it opens perfectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_SB8tmjObwC6xHKWL-2NQ.png" /></figure><p>make this kind of structure with timeline, I placed a gun into the chest as a treasure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dbBMtUcZE9las3T4GtyxQ.png" /></figure><p>Make the chest opening animation clip in it, add a sound and create an audio source in treasure chest model(drag the Treasure model into audio track audiosource line)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gk5HC2dJAkIymUhdnat_LA.png" /></figure><p>I also added another bonus sound under it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEdzIYcSqmBcIzYg_a7JTg.png" /></figure><p>Added a particle system same as in race challenge, but scaled to make it smaller</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iH6dlutTs4_z6m0R2XFmmA.png" /></figure><p>Timeline is ready now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*li5KWiN8XCy5CyGPneKfcA.png" /></figure><p>Don’t forget to turn off play on awake in director</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*lXuQtKgiOBXME6WXPqcRpw.png" /></figure><p>Also deactivate particles on start</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*5FjQmKb72ayKIyQ-iGs9pA.png" /></figure><p>We also set a trigger, a cube object with turned off mesh renderer, set the is Trigger on, with attached it script which contains ontriggerEnter — play the director command(if othe== player) as before. Also we import our 3rd person starter. Let’s also add a treasure(gun) appearing(spawning) in this script. For this we define a transform type variable to set the spawn position inside the chest.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.Playables;<br><br>public class TreasureChest : MonoBehaviour<br>{<br>    [SerializeField] private PlayableDirector _director;<br>    [SerializeField] private GameObject _gunPrefab;<br>    [SerializeField] private Transform _spawnPosition;<br>    private bool _hasOpened = false;<br>    public bool _hasOpenedPublic =&gt; _hasOpened;// to give read only access in other scripts(for UI statistics for example)<br>    //[SerializeField] private GameObject _gunholder;<br>    <br>    private void OnTriggerEnter(Collider other)<br>    {<br>        if(other.tag == &quot;Player&quot; &amp;&amp; !_hasOpened)<br>        {<br>            _director.Play();<br>            Invoke(&quot;GunSpawn&quot;, 4.1f);//calls the method with time delay<br>        }<br>    }<br>    void GunSpawn()<br>    {<br>        _hasOpened = true;<br>        GameObject _gun = Instantiate(_gunPrefab, _spawnPosition.position, Quaternion.Euler(0, 90, 90));<br>        //_gun.transform.SetParent(_gunholder.transform);//if you want to set it under certain object as a child<br>    }<br>}</pre><p>Don’t forget to add bool check to avoid to run it again and spawn another gun dublicate if you accidently enter the trigger.</p><p>Attach required elements and replace gun to spawnPosition empty obj in structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*tekpLmI4f5AMjxi8dgQc6g.png" /></figure><p>Also turn off the looping in particle system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*3fRvgLaMfRzhM7BMvTRDdA.png" /></figure><h3>Combine Cinemachine and Timeline to Open a Chest</h3><p>We always used Cinemachine and Timeline separately. What if we combine them, use cinemachine inside the timeline. We can do it and it is much more comfortable. Let’s try it. We add a VCam of chest view, it must be set while the opening and treasure spawning time. we put this VCam under the director and add it into timeline as cinemachine track</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*phInPoXkIDEeIyOo5OWv_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kgRrKFjgbgZ6k2mfNeg7Q.png" /></figure><p>Added also easy in/out, and attached cinemachineBrain, just by dragging mainCam into Cinemachine track</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*y6phdGLaIRRe67QCAdll5Q.png" /></figure><p>Also you can add some BlendList VCams or any other VCam types.</p><h3>Holding a Player During a Timeline Event</h3><p>Sometimes we might have a need to hold the player or give him certain animation during the timeline, then after the timeline player can take the control again. For this we add player into the timeline as animation track. Let’s give him an idle animation during the chest opening timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*BPXhp5hXc2fqNVSG5GMLuQ.png" /></figure><p>Don’t forget to loop the idle animation. This way is very usefull in ingame cutscenes.</p><h3>Cinematic Cutscenes</h3><p>Here I did a cutscene director timeline, in game I manually activate the director, it plays the timeline, but after timeline ends it doesn’t go back to 3rd person VCam(director is still holding the last VCam in timeline), what we can do in this situation?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j37khyeuxl-HcHQ_iHPjPQ.png" /></figure><p>I can add this the same director into it’s own timeline as activation track, in the end the director deactivates itself and Cinamachine brain sets back to our 3rd person VCam.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*en8R8ICrnZqqFffb5F5n-A.png" /></figure><h3>Challenge: Cinematic Cutscenes</h3><p>Create a cutscene between two players. The four different cameras should be:</p><ul><li>An establishing shot</li><li>An OTS from one character</li><li>An OTS from another</li><li>A close up</li></ul><p>Turn on the cutscene when the player walks into the trigger and then at the end of the cutscene, go back to the players camera.</p><p>Here everything are the same as before, the only difference is here we used blendlistVcams</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wMFyTlodReyNncKGjpuOw.png" /></figure><p>Every blendlist camera has 2 VCams, blend swaps between the with certain speed transition during the timeline. I think there is no need to repeat all other stuff.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17a619d08981" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>