<?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 Seona Bellamy on Medium]]></title>
        <description><![CDATA[Stories by Seona Bellamy on Medium]]></description>
        <link>https://medium.com/@blackcatgames?source=rss-de2c22ab3879------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ev35ARzw3FGA8bsvbcNQuw.png</url>
            <title>Stories by Seona Bellamy on Medium</title>
            <link>https://medium.com/@blackcatgames?source=rss-de2c22ab3879------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:32:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@blackcatgames/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[Using Unity’s New Input System to Simulate GetKey()]]></title>
            <link>https://blackcatgames.medium.com/using-unitys-new-input-system-to-simulate-getkey-9d6f2d62ebdc?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d6f2d62ebdc</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 02:03:12 GMT</pubDate>
            <atom:updated>2021-06-07T02:03:12.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou5CAk61lLWBp0xRrqDfxg.jpeg" /></figure><p>We’re back with the new Unity Input System again, because I ran into an interesting challenge and learned a bunch of new things. So I figured I’d share them with you. While not strictly necessary, you may find it helpful by starting with my previous articles on the system:</p><p><a href="https://blackcatgames.medium.com/unitys-new-input-system-49ee901b1422">Part 1</a> | <a href="https://blackcatgames.medium.com/moving-with-unitys-new-input-system-c55c2b622c7e">Part 2</a> | <a href="https://blackcatgames.medium.com/shooting-with-unitys-new-input-system-5441a17c8703">Part 3</a> | <a href="https://blackcatgames.medium.com/making-the-laser-uh-laser-5f8284e11cb7">Part 4</a></p><p>Now that that’s out of the way, let’s move on to the new stuff. Namely, how the #$%! do you do something similar to the old Input.GetKey()? This used to be how you did something while a key was being pressed, and it would stop happening automatically when the key was released. Similarly, Input.GetMouseButton() did the same for mouse buttons.</p><p>But, I hear you say, in Part 2 of this series we got the player moving while we were holding the direction keys! They stopped moving when we released the key! Isn’t that the same thing?</p><p>Well, yes and no. The movement action we set up in Part 2 used the “value” action type and the “Vector2” control type. This means it was leveraging a bunch of built-in logic that Unity’s new Input System provides to do just this sort of thing. But what if we wanted to change the Player’s speed if they hold down the Shift key? While the key is being held, they move at twice their normal speed. Then they go back to normal speed when the key is released.</p><p>It turned out that this was a lot harder than it looked. Then I discovered that the secret lay in the Player Input component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*tOnXXFjehC57zfNFV1d9ZQ.png" /></figure><p>When you add a Player Input component to an object, the default behaviour is “Send Messages”. There are other options, however. What we want to do is change the behaviour to “Invoke Unity Events”.</p><p>This gives us a bunch of new options, but the most important is that it lets us take advantage of the full Callback Context that the Input System provides. The Callback Context has three main options that we care about:</p><ul><li><strong>CallbackContext.started</strong> — This fires when the input is first triggered, kind of like the old Input.GetKeyDown().</li><li><strong>CallbackContext.performed</strong> — This one is a little harder to understand. It fires immediately after CallbackContext.started, then again if the value changes during the Input Action. Additionally, after it fires the status of the action is returned to “started” without CallbackContext.started actually being fired again. No, I’m not sure why they did it this way either.</li><li><strong>CallbackContext.canceled</strong> — This one fires at the end of the Input Action, sort of like the old Input.GetKeyUp().</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*38orLCJOXgGliknpc2OFxw.png" /></figure><p>So we can create a new <strong>Thruster </strong>action in our <strong>GameControl</strong>, and bind it to the Left Shift key. Then we go into our Player script and add the following variables:</p><pre>[SerializeField]<br>private float _thrusterMultiplier = 2f;<br>private float _thrustSpeed = 1f;</pre><p>Then the following method:</p><pre>public void OnThruster(InputAction.CallbackContext context)<br>{<br>    if (context.performed)<br>    {<br>        _thrustSpeed = _thrusterMultiplier;<br>    }<br>    else if (context.canceled)<br>    {<br>        _thrustSpeed = 1f;<br>    }<br>}</pre><p>Here you can see that we’re letting the Input System pass us the CallbackContext and then checking what the context is. If the context is “Performed” then we set the _thrustSpeed to our _thrustMultipler (which is serialised so that we can tweak it in the Editor if we want). If the context is “Canceled”, meaning that the key has been released, then we set it back to 1.</p><p>In the Update() loop, we now add that speed to our movement calculation:</p><pre>transform.Translate(_moveVec * _moveSpeed * _thrustSpeed * Time.deltaTime);</pre><p>If we aren’t holding the Shift key, the _thrustSpeed is 1 and so no change occurs. But while the Shift key is held down the speed changes to 2 and so the overall movement speed is doubled.</p><p>One extra thing we need to be mindful of here: All actions in a given map need to work the same way. So now that we’ve decided to go with the Unity Events style of handling we need to update our existing Player methods:</p><pre>public void OnMove(InputAction.CallbackContext context)<br>{<br>    _moveVec = context.ReadValue&lt;Vector2&gt;();<br>}<br><br> public void OnFire(InputAction.CallbackContext context)<br>{<br>    if (context.performed &amp;&amp; Time.time &gt; _nextFire)<br>    {<br>        _nextFire = Time.time + _fireRate;<br><br>        if (_tripleShotActive)<br>        {<br>            GameObject shot = Instantiate(_tripleShotPrefab);<br>            shot.transform.position = transform.position;<br>        }<br>        else<br>        {<br>            GameObject laser = PoolManager.Instance.RequestLaser();<br>            laser.transform.position = transform.position + _laserOffset;<br>        }<br><br>        onLaserFired?.Invoke();<br>    }<br>}</pre><p>Both methods now take in the CallbackContext. OnMove() is now reading the value from that context rather than being passed it directly. OnFire() is checking if the context is “Performed” (i.e. either of the fire buttons have been pressed) as well as checking if the cooldown is finished. Now these actions will continue to work as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*r8x0EpZARGbZrS4hDKK-Vg.png" /></figure><p>Before this will run, however, we need to go back to the Editor and hook this up to the Player Input component. As soon as we changed the behaviour type to “Invoke Unity Events”, we got a new set of options for Events. If we expand this we see options for our two action maps, Player and UI. If we expand the Player option we see the familiar Unity event boxes for each of our Actions — just as if we were working with a UI button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*Q4T50eh4ncr5b6bHhbU2rg.png" /></figure><p>A big gotcha here is that you don’t drag the actual script directly into the event binding. What you want to drag is the script as attached to an object in your hierarchy. In this case, both the script and the Player Input we’re using are attached to the Player object, so we drag the <strong>Player (Script)</strong> component onto the event (arrow 1). Then we can select the appropriate method from it just like we’re used to doing for UI buttons.</p><p>Helpfully, Unity groups all of the appropriate Input Events at the top of the list. This also helps you know if you forgot to set one up properly.</p><p>Now you can run your game and all the previously-working inputs should still be working. In addition, when you hold the Left Shift key while moving your player will move at double speed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d6f2d62ebdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say “No” to Magic Numbers]]></title>
            <link>https://blackcatgames.medium.com/say-no-to-magic-numbers-a1e6e98f9395?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e6e98f9395</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 22:32:20 GMT</pubDate>
            <atom:updated>2021-06-04T22:32:20.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ab_ZtPHvpZEpvGhL01rZg.jpeg" /></figure><p>One thing it’s easy to forget when writing code is that someone is going to have to read it without knowing what’s going through your head when you write it. Often, that person is simply you six months later. And (not) surprisingly, future-you is probably going to look at that code and be unable to remember exactly what past-you was thinking when you wrote it.</p><p>One of the most annoying things can be coming across a line like this one I found in the Workbench class of a game I’m building:</p><pre>public Tile GetSpawnTile()<br>{<br>    return Region.GetTileAt(tile.X + 2, tile.Y + 1);<br>}</pre><p>Huh? Why am I adding these apparently random numbers to the tile position of my workbench? Where do they come from? If I change one will it fix the problem I’m currently having or will everything blow up in my face?</p><p>I wrote this code over 9 months ago, and I couldn’t remember exactly what those numbers were for. So I spent some time changing them and testing what happened, and figured out that they were the offset for where my workbenches’ output was supposed to show up in relation to the main tile of the workbench.</p><p>So I created a new variable on the class:</p><pre>private Vector2 _outputSpawnOffset;</pre><p>And changed the return of the method to:</p><pre>return Region.GetTileAt(tile.X + _outputSpawnOffset.x, tile.Y + _outputSpawnOffset.y);</pre><p>A little more verbose, but now it doesn’t matter when I come back to it I’ll be able to tell instantly what those values represent. And it has the added advantage that if I need to reference the _outputSpawnOffset if another method further down the track I can call on the variable and know that both methods will always be using the same values.</p><p>This was, of course, an incredibly simplified example. It does illustrate a very real and common situation though. So the next time you’re tempted to just throw a number into an equation without some way of letting a future reader know what it is, just say “no”!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e6e98f9395" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complicated Pooling in Unity]]></title>
            <link>https://blackcatgames.medium.com/complicated-pooling-in-unity-165d5afb629d?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/165d5afb629d</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 22:31:07 GMT</pubDate>
            <atom:updated>2021-06-03T22:31:07.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXmnzJ6fJvYamyL37Gs30A.jpeg" /></figure><p>In my last article I looked at <a href="https://blackcatgames.medium.com/easy-pooling-in-unity-6eef64ccf541">Easy Pooling in Unity</a>. Today I’m going to expand on that a little with a more complicated use case.</p><p>I ran into this recently. The game I’m building presents the player with random powerups to give them temporary extra abilities. I wanted to pool these, but I also wanted to keep them being randomly presented to the player. Using the structure covered in the previous article, the player would keep just seeing the same one or two powerups over and over since they’re infrequent enough that the first object in the pool will almost always be deactivated by the time we need to present a new powerup.</p><p>This called for a new approach to the pooling system.</p><h3>Setting Up the Pool</h3><p>In the <strong>PoolManager</strong>, we’re going to add the following variables to the top of the class:</p><pre>[SerializeField]<br>private GameObject[] _powerupPrefabs;<br>private List&lt;GameObject&gt; _powerupPool = new List&lt;GameObject&gt;();<br>private int _powerupCounter = 0;</pre><p>Note that this time our powerup prefab holder is actually an array. Pop back into Unity and add all of your powerup prefabs into it so we can populate the array with a random assortment.</p><p>We’re also adding a counter variable. This is so we can keep track of where we are in the list.</p><p>Now we have our GeneratePowerups() method, which will once again be called from Start().</p><pre>List&lt;GameObject&gt; GeneratePowerups(int amount)<br>{<br>    for (int i = 0; i &lt; amount; i++)<br>    {<br>        GameObject powerup = Instantiate(_powerupPrefabs[Random.Range(0, _powerupPrefabs.Length)]);<br>        powerup.SetActive(false);<br><br>        _powerupPool.Add(powerup);<br>    }<br><br>    return _powerupPool;<br>}</pre><p>The only difference between this and our Enemies example is that this time we’re instantiating a random prefab from our array of powerup prefabs.</p><h3>Returning a powerup</h3><p>This is where things get really different. We can no longer just loop over the pool and find the first inactive object because that will almost always be the first one. BORING! Instead, our method looks like this:</p><pre>public GameObject RequestPowerup()<br>{<br>    if (_powerupCounter &lt; _powerupPool.Count)<br>    {<br>        if (_powerupPool[_powerupCounter].activeInHierarchy == false)<br>        {<br>            GameObject powerup = _powerupPool[_powerupCounter];<br>            powerup.SetActive(true);<br>            _powerupCounter++;<br>            return powerup;<br>        }<br>    }<br><br>    _powerupCounter = 0;<br>    GameObject firstPowerup = _powerupPool[_powerupCounter];<br>    firstPowerup.SetActive(true);<br>    return firstPowerup;<br>}</pre><p>We start by checking if the counter is less than the number of items in the pool list. If it is, then we check to see if the item in the list at the counter’s position is inactive. If it is, happy days! Set that object to active, increment the counter by one, and return the object for use.</p><p>If the counter has already gone beyond the length of the list, or if we’re on the last item and it’s somehow already active, then we’re going to loop back to the start of the list by resetting the counter to zero and returning the first powerup. For this reason I like to make my powerup pool reasonably large — maybe two or three times as large as my general default pool size. Not only does this mean that the first item has extremely little chance of still being active (powerups are only available for a fixed time before they disappear, even if they’re not collected) but it also means that the player is unlikely to notice the pattern repeating because the pattern is long and they’ve got other things to think about. Like the enemies shooting at them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165d5afb629d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Pooling in Unity]]></title>
            <link>https://blackcatgames.medium.com/easy-pooling-in-unity-6eef64ccf541?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eef64ccf541</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 00:36:28 GMT</pubDate>
            <atom:updated>2021-06-03T00:36:28.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOyx_5A67uSORT0_7nFmLw.jpeg" /></figure><p>Let’s say your game is going to send waves of enemies against the player. A wave may have 30 or 40 enemies in it, but assuming the player is actually going to be fighting back there may never be more than 5–10 enemies on screen at any given time. They die as the player shoots them, and are quickly replaced by others. The easiest way to do this is, of course, to instantiate a copy of the enemy (you did prefab them, didn’t you?) just before they appear, and then destroy that copy when the player kills it.</p><p>The trouble with this is that it’s a very resource-intensive process. And if you have a lot of it going on very rapidly, then your game can start to lag. A non-optimal situation for your player, and a non-optimal situation for you when they leave an unflattering review!</p><p>Pooling to the rescue!</p><p>At the start of the game you’ll create a set of enemy objects and then disable them so that they don’t appear on screen or do any of their usual processing. Then, when the game needs to display an enemy, you find the first inactive enemy in the list and activate them. They’ll behave just as they would if you’d instantiated them fresh, and when they die you just deactivate them again instead of destroying them. Then they’re ready to be used again.</p><h3>Setting up the PoolManager</h3><p>Create en empty object in your hierarchy called <strong>PoolManager</strong>, then create and attach a <strong>PoolManager </strong>script. Open it in your editor of choice. <a href="https://blackcatgames.medium.com/easy-singletons-in-unity-1f6905784d3f">Make the script a MonoSingleton</a>. At the top of the class, add the following variables:</p><pre>[SerializeField]<br>private int _defaultPoolSize = 10;<br>[SerializeField]<br>private GameObject _enemyPrefab;<br>private List&lt;GameObject&gt; _enemyPool = new List&lt;GameObject&gt;();</pre><p>First of all we’re defining a default size for our pool — how many objects we want to populate it to start with. Then we create a holder for the enemy prefab, and finally a list which will hold all of our pooled prefabs. Note that we’re also serialising the first two variables so that we can interact with them in Unity’s inspector. So before you forget, pop back into Unity and drag your enemy prefab into the field on the PoolManager to set up that link.</p><h3>Populating the Pool</h3><p>The first thing we need to do is to ensure that the pool gets filled with enemies when the game starts.</p><pre>void Start()<br>{<br>    GenerateEnemies(_defaultPoolSize);<br>}<br><br>List&lt;GameObject&gt; GenerateEnemies(int amount)<br>{<br>    for (int i = 0; i &lt; amount; i++)<br>    {<br>        GameObject enemy = Instantiate(_enemyPrefab);<br>        enemy.SetActive(false);<br><br>        _enemyPool.Add(enemy);<br>    }<br><br>    return _enemyPool;<br>}</pre><p>In Start() we’re simply calling on a GenerateEnemies() method and passing it the default pool size. The reason I do it this way despite the fact that I could just call _defaultPoolSize directly where I use it is because it provides me with an easy place to modify the value. Mostly in a project you will have multiple pools — one for enemies, one for bullets, one for powerups, etc. Sometimes it might make sense for, say, the bullet pool to start twice as large because there will frequently be a large number of bullets on screen at once. It’s a lot easier to see what’s happening if you have</p><pre>void Start()<br>{<br>    GenerateEnemies(_defaultPoolSize);<br>    GenerateBullets(_defaultPoolSize * 2);<br>}</pre><p>If you bury that modification in the GenerateBullets() method, it takes longer to find where that value is being modified.</p><p>Anyway, let’s look at that method now. We loop through based on the desired pool size we passed in and on each loop we instantiate the enemy prefab and immediately set it to inactive. Then we add it to our pool list. Finally, after we’re created as many enemies as we wanted, we return the list. This isn’t strictly speaking necessary — this could just as easily be a void method — but I find it’s useful to make it return the list for use in debugging. Making your life easier as a developer is never a bad thing!</p><h3>Drawing from the Pool</h3><p>When we want to use an enemy in the scene, we’ll be asking the PoolManager to give us one. This is done with the following method:</p><pre>public GameObject RequestEnemy()<br>{<br>    foreach (GameObject enemy in _enemyPool)<br>    {<br>        if (enemy.activeInHierarchy == false)<br>        {<br>            enemy.SetActive(true);<br>            return enemy;<br>        }<br>    }<br><br>    GameObject newEnemy = Instantiate(_enemyPrefab);<br>    _enemyPool.Add(newEnemy);<br><br>    return newEnemy;<br>}</pre><p>First of all we loop through our pool list to find an enemy that is currently inactive. When we find one, we make it active and return it. Pretty simple.</p><p>The second part of this method is essentially proofing against overruns. If we get through the whole list without finding an inactive enemy, that means that every enemy in the pool is currently in use. Rather than throw an error or just fail to return an enemy at all, we instantiate a new one and add it to the pool. Because this is not happening all the time, the performance hit is negligible. Plus we’re still not destroying them. In fact, we’ve just made the pool bigger to reduce the likelihood of having to do this again. And, if the player is struggling and the enemies are building up on screen for a little while, well the pool will just keep growing while they get their act together (or die).</p><p>But how do we actually use it, you ask?</p><p>In your GameManager or SpawnManager or wherever else you would normally be instantiating your enemy prefab, you’ll replace that instantiation call with the following:</p><pre>GameObject enemy = PoolManager.Instance.RequestEnemy();<br>enemy.transform.position = new Vector3(_xPos, _yPos, 0);</pre><p>We call the PoolManager’s instance and request and enemy, which we then position where we want — remember, by default it will activate in its last location if we don’t change that, and we probably want our enemies coming in from the sides rather than popping out of thin air in the middle of the battlefield. Although you could do that too I guess.</p><p>If you enemy has any variables such as health or animation state that should be reset, you’ll do that in the <strong>Enemy </strong>script itself in the OnEnable() method. This ensures it will be run every time the PoolManager activates it.</p><h3>“Killing” a Pooled enemy</h3><p>Back in the <strong>PoolManager </strong>script, we need one more method:</p><pre>public void DespawnEnemy(GameObject enemy)<br>{<br>    enemy.SetActive(false);<br>}</pre><p>This one does what it says on the tin — it sets the enemy to inactive.</p><p>To use this, in the <strong>Enemy </strong>script we go to wherever we would normally be destroying the instance and replace that destruction with the following line:</p><pre>PoolManager.Instance.DespawnEnemy(gameObject);</pre><p>If you want something to happen before the enemy pops out of existence, such as a death animation or a particle effect or even just a sound, then you can put this inside a coroutine to delay the actual despawn call until all of your fancy death effects have finished.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eef64ccf541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Singletons in Unity]]></title>
            <link>https://blackcatgames.medium.com/easy-singletons-in-unity-1f6905784d3f?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f6905784d3f</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Mon, 31 May 2021 23:03:11 GMT</pubDate>
            <atom:updated>2021-05-31T23:03:11.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okPKOwhWGWfn5eB3r8q9ww.jpeg" /></figure><p>The <a href="https://en.wikipedia.org/wiki/Singleton_pattern">Singleton Design Pattern</a> is a very useful one to have under your belt as a developer. It’s used to both enforce certain classes to only exist once in your program, and provide an easy way for other classes to interact with them. As a good rule of thumb, any class you have that includes the word “Manager” or “Controller” is probably a candidate for becoming a singleton.</p><p>Of course, if you use a lot of singletons then you’ll find yourself writing much the same code over and over (and over and over). This both breaks the principle of DRY code (Don’t Repeat Yourself) and is <em>really </em>boring! But there’s an easy way to get around this and make creating singletons a breeze.</p><h3>Introducing the MonoSingleton</h3><p>Let’s start with the full class, then we’ll go through it bit by bit and see what it does and how it does it.</p><pre>using UnityEngine;<br><br><br>public abstract class MonoSingleton&lt;T&gt; : MonoBehaviour where T : MonoSingleton&lt;T&gt;<br>{<br>    private static T _instance;<br>    public static T Instance<br>    {<br>        get<br>        {<br>            if (_instance == null)<br>            {<br>                Debug.LogError(typeof(T).ToString() + &quot; is missing.&quot;);<br>            }<br><br>            return _instance;<br>        }<br>    }<br><br><br><br>    void Awake()<br>    {<br>        if (_instance != null)<br>        {<br>            Debug.LogWarning(&quot;Second instance of &quot; + typeof(T) + &quot; created. Automatic self-destruct triggered.&quot;);<br>            Destroy(this.gameObject);<br>        }<br>        _instance = this as T;<br><br>        Init();<br>    }<br><br><br>    void OnDestroy()<br>    {<br>        if (_instance == this)<br>        {<br>            _instance = null;<br>        }<br>    }<br><br><br>    public virtual void Init() { }<br>}</pre><p>First of all, look at the class declaration. It’s a bit more complex than we’re used to seeing.</p><pre>public abstract class MonoSingleton&lt;T&gt; : MonoBehaviour where T : MonoSingleton&lt;T&gt;</pre><p>Note the use of the word abstract. This means this class can never be instantiated directly or attached to a game object. The only way to use it is to have another class inherit from it. The class is called MonoSingleton as we’d expect, but we’re also passing it a generic in the form of &lt;T&gt;. This means that we need to pass it an object type — more on this later. The class itself inherits from MonoBehaviour, which means any class which inherits from it will also be able to take advantage of MonoBehaviour like we’re used to. Finally we define that generic by basically saying we want to pass it a type of itself. This will make more sense when we see it in action later.</p><pre>private static T _instance;<br>public static T Instance<br>{<br>    get<br>    {<br>        if (_instance == null)<br>        {<br>            Debug.LogError(typeof(T).ToString() + &quot; is missing.&quot;);<br>        }<br><br>        return _instance;<br>    }<br>}</pre><p>The Singleton pattern depends on their being a public Instance that can be interacted with by the rest of the program. Here we’re setting up a private _instance variable, then providing a public getter for it. The getter also checks that there is actually an instance, and flags an error if it’s missing. The typeof(T).ToString() means that the error will use that generic T we defined above to tell you which singleton is missing its instance.</p><pre>void Awake()<br>{<br>    if (_instance != null)<br>    {<br>        Debug.LogWarning(&quot;Second instance of &quot; + typeof(T) + &quot; created. Automatic self-destruct triggered.&quot;);<br>        Destroy(this.gameObject);<br>    }<br>    _instance = this as T;<br><br>    Init();<br>}</pre><p>While the getter wanted to make sure we did have an instance, when the script first runs we want to make sure we <em>don’t</em> have an instance. Remember, this is a singleton. <a href="https://www.youtube.com/watch?v=0p_1QSUsbsM">There Can Be Only One</a>. If there is already an instance of this class, log a warning and then destroy the gameObject to make sure we only ever have the one instance. If there isn’t already an instance, then create one of the current type. Finally, run the Init() method.</p><pre>void OnDestroy()<br>{<br>    if (_instance == this)<br>    {<br>        _instance = null;<br>    }<br>}</pre><p>When the object is destroyed, make sure we clean up after ourselves by nulling any current instance. This frees us up to create a new one later if we need to without “ghost” instances hanging around.</p><pre>public virtual void Init() { }</pre><p>Finally, we create a virtual Init() method that individual implementations of the MonoSingleton can overwrite for their own purposes. I tend to use this to initialise lists and dictionaries and that sort of thing.</p><h3>MonoSingleton in action</h3><p>But how do we use this class? It’s pretty simple, as it happens. Instead of the usual class inheriting from MonoBehaviour, we do this:</p><pre>public class SpawnManager : MonoSingleton&lt;SpawnManager&gt;</pre><p>We inherit from MonoSingleton, and we pass the class itself as the generic. Now this SpawnManager will function as a singleton, and also inherits MonoBehaviour through MonoSingleton so we can write all the rest of our code just as we usually would.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f6905784d3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to host a (Unity) event]]></title>
            <link>https://blackcatgames.medium.com/how-to-host-a-unity-event-36c02051ac4d?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c02051ac4d</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Sun, 30 May 2021 23:01:08 GMT</pubDate>
            <atom:updated>2021-05-30T23:01:08.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_Cn84pbFVKEwSMJQaMcFA.jpeg" /></figure><p>The more scripts you have in your project, the more likely you are going to need to get them to talk to each other. There are several ways to do this, and the most common is with a GetComponent&lt;&gt;() call. This involves finding a specific GameObject (often by name or tag) and then accessing the script component attached to it. You can then call public variables and methods in that script.</p><p>This has a few downsides. The biggest is that GameObject.Find() and similar functions are not terribly efficient, especially in a game with lots of objects. This means that if it’s something you need to do often you can really suffer a performance hit. The second pitfall is that if you don’t do very thorough null-checking there is a chance that your whole game can fall over if you retrieve a GameObject that doesn’t have the required script attached. Lastly, it makes all of your scripts extremely dependant on each other — if one script in the sequence is removed, the whole process falls down.</p><p>Events make handling inter-script communication much easier and safer. Script A simply raises an event, saying “I’m doing a thing!”. Other scripts that care that Script A is doing the thing listen for that event, and respond accordingly when when they hear it. The important thing to note is that Script A doesn’t care who is listening and the other scripts don’t care where the event is coming from.</p><p>Let’s see it in action. Imagine you have a game where you want your player to take damage every time it collides with an obstacle. At the top of the Obstacle script, you would create an event like this:</p><pre>public static event Action onPlayerCollision;</pre><p>Further down the Obstacle script, in the OnTriggerEnter() or OnCollisionEnter() method, you would include the following:</p><pre>if (onPlayerCollision != null)<br>{<br>    onPlayerCollision();<br>}</pre><p>This says “Is anyone listening for this event? If so, do whatever you do in response.” It can also be written in a more condensed form:</p><pre>onPlayerCollision?.Invoke();</pre><p>So now that we’re raising the event, how do we listen for it and respond? Let’s start by giving our Player a basic lives system. Add the following variable to the top of the Player class:</p><pre>private int _lives = 3;</pre><p>So our player starts with three lives, and will die when those lives reach zero. Now we’ll create a Damage method to actually do this:</p><pre>void Damage()<br>{<br>    _lives--;<br><br>    if (_lives &lt; 1)<br>    {<br>        Destroy(gameObject);<br>    }<br>}</pre><p>When this method is called, we subtract one from _lives. Then we check if we’re out of lives, and if we are we destroy the player object. Note that the check is for less-than-one rather than equals-zero. This is because if the player collides with multiple objects simultaneously it is possible for the lives counter to drop below zero.</p><p>Now we need to actually tie this function to the event so that it will happen when we need it to. For this we’re introducing two of Unity’s built-in methods: OnEnable() and OnDisable().</p><pre>void OnEnable()<br>{<br>    Obstacle.onPlayerCollision += Damage;<br>}<br><br> void OnDisable()<br>{<br>    Obstacle.onPlayerCollision -= Damage;<br>}</pre><p>Unlike the Start() method that only runs once at the beginning of the scene, OnEnable() will run every time an object becomes active — so it runs at the beginning of the scene, and then if you turn the object off and then on again it runs again. So we tell the script to listen for the event whenever it’s enabled. Likewise, OnDisable() runs every time the object is turned off. So we tell the script to stop listening for the even whenever it’s disabled. This means that if you are using SetActive() to control which objects are currently running in your scene, you can be sure that the event will only be listened to by objects that are currently active.</p><p>And that’s it. Your player will now lose a life every time they collide with an obstacle, and will pop out of existence when they run out of lives. And you’ve done it without having to perform costly GetComponent() checks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c02051ac4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making the laser… uh… laser]]></title>
            <link>https://blackcatgames.medium.com/making-the-laser-uh-laser-5f8284e11cb7?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f8284e11cb7</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Fri, 28 May 2021 23:51:25 GMT</pubDate>
            <atom:updated>2021-05-28T23:51:25.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGrZPlS_qU8QSsNXkR-aDA.jpeg" /></figure><p>If you haven’t been following along with this series, I recommend you read <a href="https://blackcatgames.medium.com/unitys-new-input-system-49ee901b1422">part 1</a>, <a href="https://blackcatgames.medium.com/moving-with-unitys-new-input-system-c55c2b622c7e">part 2</a>, and <a href="https://blackcatgames.medium.com/shooting-with-unitys-new-input-system-5441a17c8703">part 3</a> before continuing. We’ll be building on the code created in those articles.</p><p>This isn’t really related to Unity’s new Input System, but since we’ve gone as far as creating our laser bolt I thought it would be nice to actually make it do something instead of just hovering in mid-air. So we’re going to make our player fire those bolts straight up towards the top of the screen a la Space Invaders.</p><h3>Moving the laser</h3><p>Start by creating a new script on the Laser prefab and opening it in your editor of choice (I use Visual Studio). At the top of the class, create the following variable:</p><pre>[SerializeField]<br>private float _speed = 8f;</pre><p>This gives us an easy way to tweak the speed that the bolt will move at while keeping it nice and private so that other classes can’t change it unexpectedly.</p><p>Now in the Update() loop add the following:</p><pre>transform.Translate(Vector3.up * _speed * Time.deltaTime);</pre><p>Vector3.up is a nice shorthand way of saying new Vector3(0, 1, 0). Not only is it shorter, but it’s clearer to see at a glance exactly what the vector is doing. And like when we moved our player, we’re using Time.deltaTime to tie the movement to realtime instead of framerate.</p><p>If you run the game now and fire your laser, you should see it moving straight up the screen.</p><h3>Clean up after yourself</h3><p>If you fired a number of laser bolts, you’ll probably have noticed that you start accumulating quite a list of them in the hierarchy. And if you click on any of those instances you’ll see that their y-position just keeps increasing — they’re firing off into forever! This is bad practise for a number of reasons, not least the fact that they’re sitting there in memory for no good reason.</p><p>Back in your Laser script, add this variable:</p><pre>private float _destroyPos = 7.5f;</pre><p>This is going to hold the point at which the laser bolt is far enough off screen that we can remove it without the player noticing. For me, this is about 7.5 on the y-axis.</p><p>Now add the following into the Update() loop, under the line where we moved the laser:</p><pre>if (transform.position.y &gt;= _destroyPos)<br>{<br>    Destroy(gameObject);<br>}</pre><p>Here we’re checking if the laser’s y-position is greater than or equal to the position at which we can safely destroy it. If it is, then we destroy it.</p><h3>Cool your lasers!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUllpykCVT7ZJ4_xif3vVg.gif" /></figure><p>At the moment, you can fire as fast as you can hit the button. While fun, this is probably not what you’re going to want in your game. It makes far more sense to restrict the rate at which the laser can be fired.</p><p>For this one, we’re returning to our Player script. Open it up and add these variables:</p><pre>[SerializeField]<br>private float _fireRate = 0.5f;<br>private float _nextFire = 0;</pre><p>_fireRate is the delay we want between shots, and we’re serialising it so that we can tweak it in the editor if we want to. _nextFire does exactly what it says on the tin: it’s the time when we can next fire a laser bolt. We’ll see how to use that next.</p><p>Find the OnFire() method we created. We’re going to put that Instantiate call into an if-statement, like this:</p><pre>if (Time.time &gt; _nextFire)<br>{<br>    _nextFire = Time.time + _fireRate;<br>    Instantiate(_laserPrefab, transform.position + _laserOffset, Quaternion.identity);<br>}</pre><p>So what are we doing here? First of all, we’re looking at Time.time, which is the time that the game has been actively running. We’re comparing it to that _nextFire variable we created and if it’s greater then we can actually do laser-firing things. Otherwise nothing happens.</p><p>If we can do laser-firing things, then we modify our _nextFire variable by adding the _fireRate (remember, this is the delay between shots) to the current time the game has been running. So say the game had been running for 30 seconds and we’d just fired a shot. If the _fireRate was 5 seconds, another shot won’t fire until the game has been running for 35 seconds (in total, not 35 seconds from now).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ghXb24XZWfRwSmvcBJ9_A.gif" /></figure><p>Then the instantiation of the laser prefab happens just as before.</p><p>Now the player fires like this, no matter how quickly they mash that fire button!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f8284e11cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shooting with Unity’s New Input System]]></title>
            <link>https://blackcatgames.medium.com/shooting-with-unitys-new-input-system-5441a17c8703?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/5441a17c8703</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Fri, 28 May 2021 00:32:14 GMT</pubDate>
            <atom:updated>2021-05-28T00:32:14.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VgbFxW9Glql9S7TO6j2jA.jpeg" /></figure><p>If you haven’t already been following along, I recommend reading <a href="https://blackcatgames.medium.com/unitys-new-input-system-49ee901b1422">part 1</a> and <a href="https://blackcatgames.medium.com/moving-with-unitys-new-input-system-c55c2b622c7e">part 2</a> of this series first. This will probably make a lot more sense if you do.</p><p>So we’ve seen how to use the new Input System to move the player around the screen. Now let’s have the player fire a laser bolt on command. We’ll tie the laser firing to both the Space key and the left mouse button.</p><p>First of all, make sure your <strong>Input Actions</strong> window is open — double-click the <strong>GameControl </strong>if it’s not.</p><h3>Setting up the action</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*N5EnL0KEKSB3RnNohoav-w.png" /></figure><p>Select the <strong>Player </strong>action map, then click the <strong>+</strong> at the top of the <em>Actions </em>column to create a new action. Rename the new action to <strong>Fire</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*66m9nUERs-imBKn7YvHzNw.png" /></figure><p>Click <strong>&lt;No Binding&gt;</strong> under the new action. In the <em>Properties</em> column, click the <strong>Path </strong>drop-down and begin typing “<strong>space</strong>”. Select <strong>Space [Keyboard]</strong> when it appears to set it as the binding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*LZ0O2VUisy082LTL_Iim8A.png" /></figure><p>Now click the <strong>+</strong> next to the <em>Fire </em>action and select <strong>Add Binding</strong>. Repeat the previous step to set up the new binding, but this time you want to bind <strong>Left Button [Mouse]</strong> in the Path field.</p><p>Your Actions column should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*sDVNeOSlc5u9CM4j5NoNuQ.png" /></figure><p>Click <strong>Save Asset</strong>!</p><h3>Creating a laser</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*eqkLDntUmhYFU4SaRf2-CQ.png" /></figure><p>Since we want to fire off a laser bolt every time the action is triggered, we’re going to need to create a prefab — Unity’s way of dealing with reusable objects. Right-click in the hierarchy and create a capsule. Set its <em>position</em> to <strong>(0,0,0)</strong> and its <em>scale </em>to <strong>(0.2,0.2,0.2)</strong>. Then drag it into the Project window.</p><p>The Laser object in the hierarchy should now be blue, indicating that it is a prefab.</p><h3>Writing the code</h3><p>Open your <strong>Player.cs</strong> script. Add the following to the list of variables at the top of the class:</p><pre>[SerializeField]<br>private GameObject _laserPrefab;</pre><p>Putting [SerializeField] above the variable declaration means that it will be editable in the Unity Inspector while still remaining a private variable. This is safer than making a variable public if you only want to edit it in Unity.</p><p>Add the following method after the OnMove() method:</p><pre>public void OnFire()<br>{<br>    Instantiate(_laserPrefab, transform.position, Quaternion.identity);<br>}</pre><p>Like when we set up the <strong>Move </strong>functionality, we’re associating this method with the <strong>Fire </strong>action by naming it OnFire(). Unlike last time, we pass no parameters to the method since this is a simple trigger.</p><p>When the trigger is activated (by pressing the space key or clicking the left mouse button) we want to create an instance of the laser bolt at the player’s position. At the moment it will just sit there and not do anything, but we can fix that later.</p><h3>Final step</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*3273BKrrv114gKOEDrc4lA.png" /></figure><p>The last thing we need to do is tell the Player script what prefab it should be instantiating. Drag the prefab from the Project window into the Laser Prefab field on the Player. Make sure you do not drag a copy from the hierarchy — in fact, if you still have a laser in the hierarchy you should delete it now.</p><p>Now you can run the game. If you move around while pressing the space key or clicking the left mouse button, you’ll leave a trail of stationery laser bolts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5441a17c8703" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving with Unity’s New Input System]]></title>
            <link>https://blackcatgames.medium.com/moving-with-unitys-new-input-system-c55c2b622c7e?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/c55c2b622c7e</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Thu, 27 May 2021 00:32:10 GMT</pubDate>
            <atom:updated>2021-05-27T00:32:10.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMs7U3x_Tbs6mIjnj1yhqg.jpeg" /></figure><p>If you haven’t already got the new Input System running in your project, check out my previous article on <a href="https://blackcatgames.medium.com/unitys-new-input-system-49ee901b1422">how to get it all set up</a>.</p><p>Now that we’re all on the same page, let’s get some player movement happening!</p><p>Start by creating a primitive shape like a cube or a sphere. This will be our Player. Create a new C# script and attach it to the object — we’ll need this later.</p><h3>Creating the Input Actions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*daIhQzVj8TIPc0tTOmWqew.png" /></figure><p>Look at the Input Actions window (double-click the GameControl you created in the previous article if it’s not already open). In the <em>Action Maps</em> column, click the <strong>+</strong> to add a new map. Rename the map to <strong>Player</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*A-TaZ5nrmRleS0p6Es1NrQ.png" /></figure><p>You’ll see in the <em>Actions </em>column that a default action has been automatically created. Rename this action to <strong>Move </strong>and click the arrow next to it to display its bindings. This should currently say &lt;No Binding&gt;. We actually want to delete this one, so right-click it and select <strong>Delete</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*04Mb-z-6KAyMnCtZGwZN8A.png" /></figure><p>Selecting our Move action gives us some information in the Properties column. Change the <em>Action Type</em> from Button to <strong>Value</strong>. This allows us to set a <em>Control Type</em>, which we’ll make <strong>Vector 2</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*H42aJgrFSCefzQJ50yz2sQ.png" /></figure><p>Now go back to the <em>Actions </em>column, click the <strong>+</strong> beside the Move action, and select <strong>Add 2D Vector Composite</strong>. This will allow us to set bindings for the four cardinal directions. Click on each of these, and in the <em>Properties </em>column select the <strong>Path </strong>drop-down. Set the values as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*8Tlyztxlk4H9IOgvLXU6qA.png" /></figure><ul><li><em>Up</em>: Up Arrow [Keyboard]</li><li><em>Down</em>: Down Arrow [Keyboard]</li><li><em>Left</em>: Left Arrow [Keyboard]</li><li><em>Right</em>: Right Arrow [Keyboard]</li></ul><p>Note that if you start typing the values, it will find them without your needing to dig through many levels of menu.</p><p>Now click <strong>Save Asset</strong>! Otherwise nothing will work.</p><h3>Let’s write some code</h3><p>Open your Player script and add the following line at the top:</p><pre>using UnityEngine.InputSystem;</pre><p>Inside the Player class, add the following variables:</p><pre>private float _moveSpeed = 10f;<br>private Vector3 _moveVec = Vector3.zero;</pre><p>_moveSpeed is the way you can control how fast the player moves. _moveVec is the direction the player is moving in and so defaults to zero so that the player is stationery if no input is being received.</p><p>In Update(), add the following code:</p><pre>transform.Translate(_moveVec * _moveSpeed * Time.deltaTime);</pre><p>This moves the player in the desired direction (_moveVec) at the desired speed (_moveSpeed) and ties the movement to realtime (Time.deltaTime) so that the player doesn’t fly off into the wide black yonder never to be seen again.</p><p>Underneath the Update() loop, add the following code:</p><pre>public void OnMove(InputValue input)<br>{<br>    Vector2 inputVec = input.Get&lt;Vector2&gt;();<br><br>    _moveVec = new Vector3(inputVec.x, inputVec.y, 0);<br>}</pre><p>You’ve associated this method with the <strong>Move </strong>action by using this pattern to name it: public void On<em>[Action Name Goes Here]</em>(). For example, a Jump action invokes OnJump(), while an Attack action invokes OnAttack().</p><p>InputValue is a new type you may not know. This class has a Get() method that you can use to access its values. In this instance, you want the 2D Vector Composite you set in the binding to calculate the movement vector.</p><p>When a player presses the <em>Up</em>, <em>Down</em>, <em>Left</em> or <em>Right</em> keys, it passes a <em>Move</em> action to this method, along with the values. Here’s how the key presses affect the values:</p><ul><li><em>Up</em>: (0, 1)</li><li><em>Down</em>: (0, -1)</li><li><em>Left</em>: (-1, 0)</li><li><em>Right</em>: (1, 0)</li><li><em>No Key</em>: (0, 0)</li><li><em>Up and Left</em>: (-1, 1)</li></ul><h3>Tying it all together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*nfZzty-XA4ylhcKRR0XbQg.png" /></figure><p>Select the Player object in the hierarchy and add a <strong>PlayerInput</strong> component. Drag your <strong>GameControl </strong>onto the component’s <em>Actions </em>field. Make sure the <em>Default Map</em> is set to <strong>Player</strong>.</p><p>Now run the game in Unity. You should be able to use the arrow keys to move the player up, down, left, and right.</p><h3>What about adding other inputs?</h3><p>Remember we talked about how easy it is to add other input options? Let’s take a look at that in action.</p><p>Suppose you wanted to allow the player to move with the WASD keys as well as the arrow keys. Start by adding a second <strong>2D Vector Composite</strong> to the <em>Move </em>action and set the four directions as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*35UsloiTARNaYC5G_6YF7w.png" /></figure><ul><li><em>Up</em>: W [Keyboard]</li><li><em>Down</em>: S [Keyboard]</li><li><em>Left</em>: A [Keyboard]</li><li><em>Right</em>: D [Keyboard]</li></ul><p>Now click <strong>Save Asset</strong> and run your game again. Without changing any code, you can now move with either the WASD keys or the arrow keys!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c55c2b622c7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity’s New Input System]]></title>
            <link>https://blackcatgames.medium.com/unitys-new-input-system-49ee901b1422?source=rss-de2c22ab3879------2</link>
            <guid isPermaLink="false">https://medium.com/p/49ee901b1422</guid>
            <category><![CDATA[input-methods]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Seona Bellamy]]></dc:creator>
            <pubDate>Wed, 26 May 2021 00:46:25 GMT</pubDate>
            <atom:updated>2021-05-26T00:47:05.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPZfl6Jkqo9UdBqa1g_b4w.jpeg" /></figure><p>Unity’s traditional input system has relied on manually building long and convoluted if-else statements into the Update() loops of our code. This is all well and good when you have only a few commands and only recognise one or two input devices, but it rapidly becomes unwieldy as you add complexity. This is where Unity’s new Input System comes to the rescue.</p><p>Instead of defining your inputs where you use them, you now create a set of Actions and Bindings — the logical meanings of an input and the input device controls. Then you have a Player Input Script that sits between this list and your code logic, linking the two together. This allows you much more ease and flexibility in how you connect different input devices, such as:</p><ul><li>Keyboard</li><li>Mouse</li><li>Pen</li><li>TouchScreen</li><li>Sensor</li><li>Joystick</li><li>GamePad</li></ul><h3>So let’s get started!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*llkXtj7h8iT4bkwrJ7W7sA.png" /></figure><p>The first thing you’ll probably need to do is to install the new system — at this point Unity does not enable it by default. Go to <strong>Window &gt; Package Manager </strong>and look through the list of available packages for <strong>Input System</strong>. Click the install button. A dialog box will appear confirming that you want to enable the new input system and disable the old one, so click <strong>Yes</strong>. Unity will now restart and when it comes back you’ll have the new input system available.</p><p>Now that we have the Input System installed, it’s time to create an Input Action. Right-click in the Project window and select <strong>Create &gt; Input Action</strong>. Give the new action a name such as “GameControl” and then double-click it. This opens up the Input Actions window where we can start setting things up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtcFmaKnwsE5N9-cWXMZPQ.png" /></figure><p>This window has four important features:</p><ol><li><em>Action Maps</em>: Groups of actions that occur in the game. You can group actions for different purposes, like player, gameplay or UI.</li><li><em>Actions</em>: The list of actions and bindings associated with the selected Action Map. In this panel, you create, modify or delete actions and bindings.</li><li><em>Properties</em>: Edit the action or binding properties in this panel, such as the type of action and the controls you associated with the binding.</li><li><em>Save Assets</em>: This is a very important function. You must click <em>Save Asset</em> after making any changes to the <em>Input Action Asset</em>. If you forget to save, the setting won’t work. Thus, you won’t see the expected result and may think there’s a bug in the code.<br>You can switch on <em>Auto Save</em> to prevent the problem, but it’s quite slow.</li></ol><p>So now we’re set up with the new system and have a basic idea of how it all hangs together. In the next article, we’ll look at using it to implement some player movement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49ee901b1422" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>