<?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 Caner Nurdag on Medium]]></title>
        <description><![CDATA[Stories by Caner Nurdag on Medium]]></description>
        <link>https://medium.com/@canernurdag?source=rss-624ef0415cc4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f1f4N_2tMwA8wNYis86HxA.jpeg</url>
            <title>Stories by Caner Nurdag on Medium</title>
            <link>https://medium.com/@canernurdag?source=rss-624ef0415cc4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:25:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@canernurdag/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[Unity — Complete BattleRoyale Mobile Game: Implementation of Zenject, UniRx, UniTask, Async…]]></title>
            <link>https://medium.com/@canernurdag/unity-complete-battleroyale-mobile-game-implementation-of-zenject-unirx-unitask-async-d22e187fa2a?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d22e187fa2a</guid>
            <category><![CDATA[zenject]]></category>
            <category><![CDATA[unirx]]></category>
            <category><![CDATA[unitask]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Sat, 04 May 2024 16:08:24 GMT</pubDate>
            <atom:updated>2024-05-04T16:08:24.989Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unity — Complete BattleRoyale Mobile Game: Implementation of Zenject, UniRx, UniTask, Async Addressables, Scriptable Objects, Unit Testing, and More.</h3><h4>Source code of the project: <a href="https://github.com/canernurdag/Unity_BattleRoyale_SinglePlayer">GitHub</a></h4><h3>Gameplay</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-Q_IefK9Xgo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-Q_IefK9Xgo&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/628f7f106b89ebbaf8c65434bd895cac/href">https://medium.com/media/628f7f106b89ebbaf8c65434bd895cac/href</a></iframe><h3>Intro</h3><p>As a professional Unity user, I am always willing to learn and try out new game-development techniques. I think creating an actual product is the best approach to accomplish this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*IWXCasGXYVnHTyUB" /></figure><p>Therefore, I have developed a complete game that resembles<strong> Brawl Stars</strong>, a huge hit from<strong> Supercell</strong>. For this article and the ones that follow, I will be using this game to implement and experiment with third-party libraries, frameworks, etc.</p><p>In this article, I focus mostly on<strong><em> Zenject, UniRx, UniTask, Addressables, and Unit testing</em></strong>.</p><p>[CS 1.6 mode: on]<strong> Go, Go, Go</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*6OY-fTxcOvIc4-R4fcJ_OQ.png" /></figure><h3>Architect</h3><h4>Architect — Layers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*xFRLmrZIagJpphg_sgWfjw.png" /></figure><p><strong>1. Object Communication Layer: </strong>Instead of “<strong><em>Service Locator System</em></strong>”, I use “<strong><em>Zenject</em></strong>” in this project.<em> (In the following chapters, I will be explaining Zenject in detail.)</em></p><p><strong>2. Manager Layer: </strong>They are responsible for systems that maintain the application.</p><p><strong>3. Controller Layer: </strong>They are mostly responsible for controlling actor objects inside a logic.</p><p><strong>4. Actors Layer ( similar to Unreal Engine approach): </strong>Characters, UI objects, props, etc.</p><h4>Architect — Programming Paradigm</h4><p>The main paradigm is object-oriented programming.<br>(<strong><em>Inheritance, encapsulation, polymorphism,</em></strong> etc).</p><p>In addition to OOP, rarely the reactive programming paradigm is used.</p><h4>Architect — Design Patterns</h4><p>On top of Unity’s architect, the patterns below are used in the project.</p><p><strong>Observer Pattern: </strong>Example: Used for sending signals to observer objects when a user joins a game session or leaves a game session.</p><p><strong>Factory Pattern: </strong>Example: Used to create Characters via Zenject Factory. The major benefit of using the Zenject factory is that all dependencies are injected into instantiated objects.</p><p><strong>Object Pool Pattern: </strong>Example: Used for bullets, of which I need many concurrently and repeatedly.</p><p><strong>State Pattern: </strong>Example: Used for character attack state machine and character movement state machines.</p><h4>Architect — Object Dependencies</h4><p>There are 2 types of dependencies:</p><p><strong><em>1. Direct References: </em></strong>Which we use as drag&amp;drop in Unity editor. I think everyone knows this.</p><p><strong><em>2. Injected Dependencies:</em></strong> Which Zenject sets all the required dependencies.</p><h4>Architect —Data</h4><p>1. <strong><em>Predefined data</em></strong> is mostly stored in <strong><em>Scriptable Objects</em></strong>. However, sometimes I prefer to store on prefabs, which is quicker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*5LYkZaadOJNnWih9O25fzg.png" /></figure><p>2. <strong><em>Save data</em></strong> is a single serializable object. Loading and saving processes are done through <strong><em>SaveSystem</em></strong>.</p><pre>namespace Assets.Scripts.Runtime.Systems.SaveSystem<br>{<br>    [Serializable]<br>    public class SaveState<br>    {<br>        #region SAVE DATA<br>        public string BundleVersion;<br>        #endregion<br><br>        #region USER DATA<br>        public int UserId;<br>        public string UserName;<br>        public int TotalMoneyAmount;<br><br>        public CharacterVisual.Type SelectedCharacterVisualType;<br>        public Weapon.Type SelectedWeaponType;<br>        public List&lt;SaveDataType_CharacterVisual&gt; SaveDataType_CharacterVisuals;<br>        public List&lt;SaveDataType_WeaponVisual&gt; SaveDataType_Weapons;<br><br>        public int ExperienceLevel;<br>        public int ExperienceAmount;<br>        #endregion<br><br>        #region PREF DATA<br>        public float SFXLevel;<br>        public float MusicLevel;<br>        public bool IsVibrationOn;<br>        public bool IsNoAdsOn;<br>        #endregion<br>    }<br>  }</pre><h3>Implementations</h3><h4>#Zenject</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*TUjL2tG-ryKnnP9uRFbK6w.png" /><figcaption><a href="https://medium.com/technology-nineleaps/simplify-your-code-with-dependency-injection-in-c-9f1865d322f8">Ref</a></figcaption></figure><p>Zenject defines itself as below.</p><blockquote><a href="https://github.com/modesttree/Zenject">Zenject </a>is a lightweight highly performant dependency injection framework built specifically to target Unity 3D.</blockquote><p>Although Zenject seems to be just a DI framework, I view Zenject as a more comprehensive solution. The reason for that is that Zenject has integrated:</p><ul><li><strong>Memory Pool</strong> (Object Pool): Due to its very time-consuming and complex structure, I find my event system more practical.</li><li><strong>Factory:</strong> Well designed.</li><li><strong>Signal System (</strong>Event System): Well designed. It is very similar to other event systems.</li></ul><p>You may find implementation for all of them in the GitHub <a href="https://github.com/canernurdag/Unity_BattleRoyale_SinglePlayer">repository</a>.</p><p><strong>-How Zenject Works-</strong></p><p>In the runtime environment, <strong><em>Zenject Context</em></strong> and<strong><em> Zenject Kernel </em></strong>classes initialize themselves before all other classes to guarantee the correct script execution order. This is the same in my Service Locator approach. No surprise :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*V9Sf6rTn8zZAa5-lNfyK2g.png" /></figure><p>After that, Zenject instantiates the “<strong><em>ProjectContext</em></strong>” from the <strong><em>Resources</em></strong> folder as “DontDestroyOnLoad”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ktd98bmjCy8hZNqhKAvBBQ.png" /></figure><p>The “<strong><em>ProjectContext</em></strong>” mainly includes 2 important things: Zenject installers and my managers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*Nwh-jz65nJ72fY36CH-X0w.png" /></figure><p>For the logic of how dependencies are supposed to be injected, we use Zenject’s “<strong><em>Installers</em></strong>” which are handled within “<strong><em>Project Context</em></strong>” or “<strong><em>Scene Context</em></strong>”.</p><blockquote>PS: <strong>Scene Context</strong> is scene-dependent whereas <strong>Project Context</strong> is always live in “DontDestroyOnLoad”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*QqZYrVM3Ckk4FSrUZuWNhw.png" /></figure><p>Let me give some injection examples quickly.</p><p>Case 1: When the <strong><em>ManagerScene</em></strong> requires the <strong><em>ManagerGame </em></strong>object.</p><p>1. We bind ManagerGame in a monoinstaller script by overriding the InstallBindings() method.</p><pre>public class Project_Manager_Installer : MonoInstaller<br>{<br><br>    public override void InstallBindings()<br>    {<br>        Container.Bind&lt;ManagerGame&gt;().FromComponentInHierarchy().AsSingle();<br>    }<br>}</pre><p>2. Similar to C# construct method, we need to create a method with [Inject] attribute.</p><pre>public class ManagerScene : MonoBehaviour<br>{<br>    #region REFERENCES<br>    private ManagerGame _managerGame;<br>    #endregion<br><br>    [Inject]<br>    public void Construct(ManagerUi managerUi)<br>    {<br>        _managerGame = managerGame;<br>    }<br>}</pre><p>Case 2: The <strong><em>StartCountDown() </em></strong>method of the <strong><em>ControllerMatch </em></strong>class needs to subscribe to the <strong><em>SignalGameStateChange </em></strong>signal.</p><p>1- A “<strong><em>SignalGameStateChanged</em></strong>” is declared in the <strong><em>InstallBindings()</em></strong> method.</p><p>2- The <strong><em>StartCountDown()</em></strong> method subscribes to “<strong><em>SignalGameStateChanged</em></strong>” by using the Container’s <strong><em>BindSignal()</em></strong> method.</p><pre>public override void InstallBindings()<br>{<br>   SignalBusInstaller.Install(Container);<br><br>   //SIGNAL DECLARATION<br>   Container.DeclareSignal&lt;SignalGameStateChanged&gt;();<br><br>   //SIGNAL BINDINGS<br>   Container.BindSignal&lt;SignalGameStateChanged&gt;()<br>            .ToMethod&lt;ControllerMatch&gt;(x =&gt; x.StartCountdown)<br>            .FromResolve();<br>}</pre><p>3- Signal firing example.</p><pre>public void SetCurrentGameStateType(GameStateType gameStateType)<br>{<br>   _currentGameStateType = gameStateType;<br>   _signalBus.Fire(new SignalGameStateChanged(gameStateType));<br><br>}</pre><p>There are many ways to inject dependency in Zenject. Since there is amazing documentation, I will not explain each of them.</p><blockquote>Please refer to the cheat sheet. <a href="https://github.com/modesttree/Zenject/blob/master/Documentation/CheatSheet.md">https://github.com/modesttree/Zenject/blob/master/Documentation/CheatSheet.md</a></blockquote><p><strong>-PROs Zenject-</strong></p><ul><li>Separation of dependency logic from components</li><li>Avoid code repeating for some objects. =&gt; Case: Different objects call GetCompnent/GetComponentInChildren etc for the same object.</li><li>Amazing documentation</li><li>Avoiding null references because of script execution order. (Sometimes we can get null references in builds where everything is fine in Editor’s Play mode)</li></ul><p><strong>-CONs Zenject-</strong></p><ul><li>Extra tons of classes. Sometimes I feel Zenject is an over-engineering :)</li><li>Async problems</li></ul><h4>#UniRx — Reactive Programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*WQWtmqjQP2jqCptIzfDKKA.png" /><figcaption><a href="https://reactivex.io/documentation/operators/map.html">Ref</a></figcaption></figure><blockquote><strong>Reactive programming</strong> is a declarative programming paradigm concerned with data streams and the propagation of change. (<a href="https://en.wikipedia.org/wiki/Reactive_programming">Ref</a>)</blockquote><p>On the other hand, <strong><em>UniRx </em></strong>defines itself as below.</p><blockquote><a href="https://github.com/neuecc/UniRx">UniRx </a>(Reactive Extensions for Unity) is a reimplementation of the <a href="https://github.com/dotnet/reactive">.NET Reactive Extensions</a>.</blockquote><p>From my perspective, <strong><em>Rx is working with data streams</em></strong>. And, the structure looks like Linq.</p><p>Check the example below.</p><p>1- The data stream defined as <strong><em>ObservableInputForPlayerMovement </em></strong>is created as <strong><em>IObservables&lt;Vector2&gt; </em></strong>in ManagerInput.</p><p>2- Data stream value logic is determined in Awake.</p><pre>ManagerInput.cs <br><br> #region Cache<br>  public IObservable&lt;Vector2&gt; ObservableInputForPlayerMovement { get; private set; }<br>  public IObservable&lt;Vector2&gt; ObservableInputForPlayerAttack { get; private set; }<br><br>  public float InputCorrectionAccordingToCameraAngle { get; private set; }<br>  #endregion<br><br><br>  private void Awake()<br>  {<br>      ObservableInputForPlayerMovement = this.UpdateAsObservable()<br>          .Select(_ =&gt; InputProviderForPlayerMovement.GetCurrentMobileInput() * InputCorrectionAccordingToCameraAngle);<br><br>      ObservableInputForPlayerAttack = this.UpdateAsObservable()<br>          .Select(_ =&gt; InputProviderForPlayerAttack.GetCurrentMobileInput() * InputCorrectionAccordingToCameraAngle);<br><br>  }</pre><p>3- In <strong>CharacterMovementPlayer.cs</strong>, character movement logic according to the data stream is determined.</p><pre>CharacterMovementPlayer.cs<br><br>private void Start()<br>{<br>    Movement_RX();<br>}<br><br>private void Movement_RX()<br>{<br>    if (_managerInput == null) return;<br><br>    _managerInput.ObservableInputForPlayerMovement<br>        .Where(_ =&gt; _managerGame.CurrentGameStateType == GameStateType.GameStarted)<br>        .Where(_ =&gt; _characterGameplay.IsAlive)<br>        .Subscribe(input =&gt;<br>        {<br>            //In order to satisfy abstract class parameter, we cast Vector2 to Vector3. Z Value is 0.<br>            Vector3 inputV3 = (Vector3)input;<br><br>            if (input == Vector2.zero)<br>            {<br>                if (IsMoving)<br>                {<br>                    SetIsMoving(false);<br>                    _characterPlayerMovementStateMachine.SetCurrentState(new CharacterMovementIdleState(_characterPlayerMovementStateMachine));<br>                }<br><br>            }<br>            else if (input != Vector2.zero)<br>            {<br>                if (!IsMoving)<br>                {<br>                    SetIsMoving(true);<br>                    _characterPlayerMovementStateMachine.SetCurrentState(new CharacterMovementMoveState(_characterPlayerMovementStateMachine));<br>                }<br>                Move(inputV3);<br>            }<br><br><br>            if (!_managerInput.InputProviderForPlayerAttack.IsInputExist())<br>            {<br>                if (_characterWeaponAttack.GetActiveWeaponAttack().IsWeaponAttackFinished)<br>                {<br>                    Rotate(inputV3);<br>                }<br>            }<br><br>        });<br><br>    _managerInput.ObservableInputForPlayerAttack<br>        .Where(_ =&gt; _managerGame.CurrentGameStateType == GameStateType.GameStarted)<br>        .Where(x =&gt; x != Vector2.zero)<br>        .Where(_ =&gt; _characterGameplay.IsAlive)<br>        .Subscribe(input =&gt;<br>        {<br>            RotateForAttack(input);<br><br>        });<br>}</pre><p><strong>-PROs UniRx-</strong></p><ul><li>Ready Unity-specific methods</li><li>Async ability</li><li>Linq style structure</li></ul><p><strong>-CONs UniRx-</strong></p><ul><li>Lack of documentation and tutorials</li><li>Painful debugging.</li></ul><h4>#UniTask</h4><p>The coroutines are the first thing we consider when we need async operations in Unity. Nevertheless, the coroutines have lots of weaknesses.</p><p>So, UniTask is a great alternative to coroutines.</p><blockquote><a href="https://github.com/Cysharp/UniTask">UniTask </a>is a library that provides an efficient allocation free async/await integration for Unity.</blockquote><p>Look at the example of an addressables async operation.</p><pre>public async UniTask&lt;GameObject&gt; GetAndInstantiateGameObjectAsync(AssetReference assetReference)<br>{<br>    var asyncOperationHandle = assetReference.InstantiateAsync().WithCancellation(this.GetCancellationTokenOnDestroy());<br>    var result = await asyncOperationHandle;<br><br>    return result;<br>}</pre><pre>ActiveWeaponGameObject = await _managerAddressables.GetAndInstantiateGameObjectAsync(weaponAssetReference);</pre><p><strong>UniTask vs Coroutine</strong></p><ul><li><strong>Return Value: </strong>UniTask can have a return value whereas coroutine returns only IEnumerator.</li><li><strong>Memory allocation: </strong>Coroutine is more expensive in terms of memory allocation. (I encountered this issue in one of the previous voxel games.)</li><li><strong>Availability: </strong>Objects must be inherited from Monobehavior for coroutines.</li><li><strong>Lifetime management: </strong>Coroutines automatically stop when the object is destroyed whereas UniTask needs a cancelation. “.WithCancellation(this.GetCancellationTokenOnDestroy())”</li><li><strong>Handle Exception: </strong>Coroutines are not capable of handling exceptions.</li></ul><blockquote>A good <a href="https://blog.matheusamazonas.net/posts/coroutines_async_await">article</a> on UniTask vs Coroutine</blockquote><h4>#Addressables</h4><p>In this article, we will cover why addressables are important in terms of dependency management and memory management. Content packing and bundles are not the subject of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*E2E8N5vzZ6G5C9iOYhBsqQ.png" /></figure><p><strong>1- Memory Management</strong></p><p>[SerializeField] is a very risky attribute. The reason is Unity loads every object you reference to the memory, even if they are not used. So, the solution is the addressables.</p><p>The addressables system give us an ability to load/unload objects on demand. The key is using addresses instead of references.</p><p><strong>2- Dependency Management</strong></p><p>The addressables system give us an ability to load/unload all dependencies of an object in the same time.</p><p>Check the example below.</p><pre>[field: SerializeField] public AssetReferenceAudioClip AR_TriggerAudioClip { get; protected set; }<br>public AudioClip TriggerAudioClip { get; protected set; }<br>[field: SerializeField] public AssetReferenceAudioClip AR_HitAudioClip { get; protected set; }<br>public AudioClip HitAudioClip { get; protected set; }<br><br><br>protected virtual void Awake()<br>{<br>    _ = SetTriggerAudioClip();<br>    _ = SetHitAudioClip();<br>    <br>}<br><br>protected async UniTaskVoid SetTriggerAudioClip()<br>{<br>    if (AR_TriggerAudioClip == null) return;<br>    if(_managerAddressables == null) return;<br><br>    TriggerAudioClip = await _managerAddressables.GetAudioClipAsync(AR_TriggerAudioClip);<br>}<br><br>protected async UniTaskVoid SetHitAudioClip()<br>{<br>    if (AR_HitAudioClip == null) return;<br>    if (_managerAddressables == null) return;<br><br>    HitAudioClip = await _managerAddressables.GetAudioClipAsync(AR_HitAudioClip);<br>}</pre><pre>namespace Assets.Scripts.Runtime.Core.Managers.Manager_Addressables<br>{<br>    public class ManagerAddressables : MonoBehaviour<br>    {<br>        #region OBJECT FUNCTIONS<br> <br>        public async UniTask&lt;GameObject&gt; GetAndInstantiateGameObjectAsync(AssetReference assetReference)<br>        {<br>            var asyncOperationHandle = assetReference.InstantiateAsync().WithCancellation(this.GetCancellationTokenOnDestroy());<br>            var result = await asyncOperationHandle;<br> <br>            return result;<br>        }<br> <br>        public async UniTask&lt;AudioClip&gt; GetAudioClipAsync(AssetReferenceAudioClip assetReferenceAudioClip)<br>        {<br>            var asyncOperationHandle = assetReferenceAudioClip.LoadAssetAsync&lt;AudioClip&gt;().WithCancellation(this.GetCancellationTokenOnDestroy());<br>            var result = await asyncOperationHandle;<br> <br>            return result;<br>        }<br> <br>        public void ReleaseAndDestroy(GameObject addressedGameObject)<br>        {<br>            if (!Addressables.ReleaseInstance(addressedGameObject))<br>                Destroy(addressedGameObject);<br>        }<br> <br>        #endregion<br>    }<br> <br>    [Serializable]<br>    public class AssetReferenceAudioClip : AssetReferenceT&lt;AudioClip&gt;<br>    {<br>        public AssetReferenceAudioClip(string guid) : base(guid)<br>        {<br>        }<br>    }<br>}</pre><p><strong>-Async Addressables &amp; Zenject Conflict-</strong></p><p>Case: <strong><em>ActiveWeapon </em></strong>variable, which Zenject needs to inject into some other objects, has to be ready in the first frame due to Zenject’s nature. On the other hand, an async addressables is needed for initalizing ActiveWeapon. This was the problem I encountered.</p><p>Therefore, I wrote an adapter class <strong><em>AddressableAdapterWeapon </em></strong>for Zenject to inject dependency to <strong><em>CharacterGameplay.</em></strong></p><pre>public class CharacterGameplay : Character, ICharacterGameplay<br>{<br>  protected IEnumerator InitCharacterWeapon()<br>  {<br>      var weaponType = User.Userdata.WeaponType;<br>      CharacterWeapon.SetActiveWeapon(weaponType);<br>      while (CharacterWeapon.GetActiveWeapon() == null)<br>      {<br>          yield return null;<br>      }<br>  <br>      var weaponAttack = CharacterWeapon.GetActiveWeapon().GetComponent&lt;WeaponAttack&gt;();<br>      weaponAttack.SetWeaponType(weaponType);<br>      CharacterWeaponAttack.SetActiveWeaponAttack(weaponAttack);<br>      CharacterWeaponAttack.InitChararcterWeaponAttack();<br>  }<br>}<br><br></pre><pre>public class AddressableAdapterWeapon : AddressableAdapter<br>{<br>  public async void SetActiveWeapon(Weapon.Type weaponType, Action callback)<br>  {<br>      if (IsAsyncOn) return;<br>      ReleaseInstances();<br>  <br>      var weaponAssetReference = GetWeaponAssetReference(weaponType);<br>      if (weaponAssetReference != null)<br>      {<br>          ActiveWeaponGameObject = await _managerAddressables.GetAndInstantiateGameObjectAsync(weaponAssetReference);   <br>          if (callback != null) callback();<br>      }<br>  }<br>}<br><br></pre><p>By the way, as I observe in Blizzard’s <a href="https://overwatch.blizzard.com/en-us/">Overwatch</a>, a character’s abilities and behaviours are ready in the beginning of the first frame, even though async loading operations of materials, shaders, textures, sounds are not finished. This makes sense to me.</p><p><strong>-PROs Addressables-</strong></p><ul><li>Excellent memory management</li></ul><p><strong>-CONs Addressables-</strong></p><ul><li>Extra works such as builds etc.</li></ul><h4>#Test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*aPiKeYhYy0tp6xgyCnqvaQ.png" /></figure><p>Unit tests and Integration tests are practical solutions that avoid potential future bugs. So, I highly recommend them.</p><p>Let’s see an example.</p><pre>namespace Assets.Scripts.Runtime.Tests<br>{<br>    public class TestPlayerMovement<br>    {<br>        [UnityTest]<br>        public IEnumerator CharacterGameplayPlayerMovement_WhenUpInput_ExpectTransformPositionZIsHigher_Test()<br>        {<br>            //ARRANGE <br>            GameObject playerGO = new GameObject(&quot;Player&quot;);<br>            CharacterMovementPlayer characterMovementPlayer = playerGO.AddComponent&lt;CharacterMovementPlayer&gt;();<br> <br>            Rigidbody rigidbody = playerGO.AddComponent&lt;Rigidbody&gt;();<br>            rigidbody.useGravity = false;<br> <br>            CapsuleCollider capsuleCollider = playerGO.AddComponent&lt;CapsuleCollider&gt;();<br> <br>            characterMovementPlayer.Test_SetRigidbody(rigidbody);<br>            characterMovementPlayer.Test_SetMockCharacterControllerSettings();<br> <br>            //ACT<br>            float inputDuration = 0.5f;<br>            Vector3 upInput = new Vector3(0, 1, 0);<br>            while (inputDuration &gt; 0)<br>            {<br>                inputDuration -= Time.deltaTime;<br>                characterMovementPlayer.Move(upInput);<br>                yield return null;<br>            }<br> <br>            yield return new WaitForSeconds(inputDuration);<br> <br>            //ASSERT<br>            Assert.IsTrue(playerGO.transform.position.z &gt; 0f);<br>        }<br>    }<br>}</pre><p>Let’s see another example. In this case, we need a mock for ICharacter interface. <a href="https://nsubstitute.github.io/">NSubstitute</a> is an excellent fixer.</p><pre>namespace Assets.Scripts.Runtime.Tests<br>{<br>    public class TestCharacterAttack<br>    {<br>        [Test]<br>        public void CharacteAttackPlayer_WhenNoAmmo_ExpectAttackFails()<br>        {<br>            //ARRANGE <br>            GameObject playerGO = new GameObject(&quot;Player&quot;);<br>            CharacterAttackPlayer characterAttackPlayer = playerGO.AddComponent&lt;CharacterAttackPlayer&gt;();<br>            characterAttackPlayer.TestSetAllAmmosEmpty();<br> <br>            ICharacter character = Substitute.For&lt;ICharacter&gt;();<br>            characterAttackPlayer.TestSetCharacter(character);<br> <br>            CharacterPlayerAttackStateMachine characterPlayerAttackStateMachine = playerGO.AddComponent&lt;CharacterPlayerAttackStateMachine&gt;();<br>            characterPlayerAttackStateMachine.SetCurrentState(new CharacterAttackIdleState(characterPlayerAttackStateMachine));<br> <br>            //ACT<br>            var signalCharacterAttack = new SignalCharacterAttack(character, 0.1f);<br>            characterAttackPlayer.SetAttackState(signalCharacterAttack);<br> <br>            //ASSERT<br>            Assert.AreNotEqual(characterPlayerAttackStateMachine.CurrentState.GetType(), typeof(CharacterAttackAttackState));<br>        }<br> <br> <br>    }<br>}</pre><blockquote>PS: Before testing in Unity, we need to create assemble definitions for scripts we created. However, the 3rd party dev assets may not have assembly definitions. So, we need to create for them as well. Besides, assembly definitions do not respect “Editor” folders. So, do not forget to create assembly definitions for Editor classes.</blockquote><p><strong>-PROs Testing-</strong></p><ul><li>Efficient method prevents from bugs</li></ul><p><strong>-CONs Testing-</strong></p><ul><li>Required extra time</li></ul><h3>Extras</h3><p>In the project, you may find the implementation of</p><ul><li>Animation System: Locomotion, Animation Layers</li><li>Scriptable Objects: Data container</li><li>Cinemachine: State Driven Camera, Camera Shake, Ghost Object logic</li><li>Input System: Implementation of concurrent 2 joystick</li><li>UI System: Responsive Ui implementation through Layout Groups and Layout Element</li></ul><h3>References</h3><ul><li><strong><em>Used 3rd party dev assets:</em></strong></li><li>1- <a href="https://assetstore.unity.com/packages/tools/animation/dotween-hotween-v2-27676">DOTween</a></li><li>2- <a href="https://assetstore.unity.com/packages/tools/utilities/easy-save-the-complete-save-data-serializer-system-768">Easy Save</a></li><li>3- <a href="https://github.com/modesttree/Zenject/tree/master">Zenject</a></li><li>4- <a href="https://github.com/neuecc/UniRx">UniRx</a></li><li>5- <a href="https://github.com/Cysharp/UniTask">UniTask</a></li></ul><p><strong><em>Used 3rd party art assets:</em></strong></p><ul><li>1- <a href="https://assetstore.unity.com/packages/vfx/particles/epic-toon-fx-57772">Epic Toon Fx</a></li><li>2- <a href="https://assetstore.unity.com/packages/vfx/shaders/flat-kit-toon-shading-and-water-143368">FlatKit</a></li><li>3- <a href="https://assetstore.unity.com/packages/3d/environments/fantasy/battle-arena-cartoon-assets-144448">Battle Arena — Cartoon assets</a></li><li>4- <a href="https://assetstore.unity.com/packages/3d/characters/humanoids/battle-royale-hero-pbr-189511">Battle Royale Hero PBR</a></li><li>5- <a href="https://github.com/Henrylq/Brawl-Stars-SFX">Brawl Stars -SFX</a></li><li>6- <a href="https://assetstore.unity.com/packages/2d/gui/gui-pro-casual-game-176695">GUI Pro — Casual Game</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d22e187fa2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity — How to Create A Base Framework For Mobile Games]]></title>
            <link>https://medium.com/@canernurdag/unity-how-to-create-a-base-framework-for-mobile-games-b2d936660df0?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d936660df0</guid>
            <category><![CDATA[mobile-games]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 13:59:17 GMT</pubDate>
            <atom:updated>2023-07-07T13:59:17.228Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unity — How to Create A Base Framework For Mobile Games</h3><p>It has been a too long for me to write an article here. Finally, it is time to share something new here :)</p><p>Today, I am going to explain step by step how to create a base framework for your upcoming mobile games. You do not need to invent the wheel for each repo again and again. Besides, the framework will increase team efficiency and harmony by forcing all Devs to use the same classes/functions in common.</p><p>Before everything, please keep in mind that this article and github repo are prepared according to my needs. So, it is better for you to adjust/extend it according to your needs.</p><blockquote>Repo Link: <a href="https://github.com/canernurdag/Tolian_UnityFrameWork/tree/main/Scripts">https://github.com/canernurdag/Tolian_UnityFrameWork/tree/main/Scripts</a></blockquote><p>On the other hand, there is no such way which is the best one to satisfy all of gamedev limitations. So, let’s prioritise your project needs first.</p><h4>1- Folder Structure</h4><p>At first glance, the folder structure should be well organized in the beginning of the project since all contributors of the project have to figure the asset folder out easily. It is very crucial. Moreover, with the upcoming commits, the folder count will be growing rapidly. <strong>Therefore, the first thing we should consider is the folder structure.</strong></p><p>At that point, let me quickly some tips and best practices here.</p><p><strong>1- </strong>Some folder names are <strong>special </strong>and unique for Unity Engine. So, use them as designed by Unity.</p><blockquote>Please refer to the link: <a href="https://docs.unity3d.com/Manual/SpecialFolders.html">https://docs.unity3d.com/Manual/SpecialFolders.html</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*4nMDkibRHMqwfPkgEOM4Yg.png" /><figcaption>My folder structure</figcaption></figure><p><strong>2-</strong> Some folder names are very common among Unity developers. So, it is better to use these names.</p><blockquote>For example, Prefabs, Scripts, Art etc.</blockquote><p><strong>3- </strong>Keep the 3rd party assets in a different folder, such as plugins.</p><blockquote>In order to reduce compiling time, a specific “3rd Party folder” makes us able to create an assembly definition file in case they do not have any.</blockquote><p><strong>4- </strong>It is a good practice to align script folder with the namespace structure.</p><blockquote>At top level, <strong>Editor</strong>, <strong>Runtime </strong>and <strong>Test </strong>folders should be enough unless you need any extra specific folders.</blockquote><blockquote>Please refer to my framework to figure out the script folders as an example: <a href="https://github.com/canernurdag/Tolian_UnityFrameWork/tree/main/Scripts">https://github.com/canernurdag/Tolian_UnityFrameWork/tree/main/Scripts</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*1zf-IqQnEMaCji7ZbC8oPw.png" /><figcaption>Top Level Of Scripts Folder</figcaption></figure><p>5- Use AssetPostProcessor for setting preferences automatically when importing an asset. This will speed up the importing processes to a specific folder.</p><blockquote>Please refer to: <a href="https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html">https://docs.unity3d.com/ScriptReference/AssetPostprocessor.html</a></blockquote><h4>2- Scene Structure</h4><p>The second subject is the scene structure. Before diving into the details, we should analyze the needs and create scene structures accordingly.</p><p>-The first structure I see is <strong>scene by scene</strong> with common prefabs. All scenes are independant. However, I do not suggest this approch. This is the easiest and the basic one to develop but the worst to maintain.</p><p>-The second structure is <strong>one starter scene</strong> and the other level scenes. In my opinion, this is a good one for level by level games. The starter scene prepares the game and creates DontDestroyOnLoad objects which will be active during the game. I am going to give more details in this article.</p><p>-The third sturcture, <strong>one starter scene </strong>and additive scenes on top of it.<br>This approach can be good for larger games which may require more optimization. Especially, it can be very powerful with Addressables. However, this structure requies more experince. The communication of the gameobjects from different scenes can be an issue here.</p><p>Let me explain my structure.</p><ul><li>I have a starter scene that includes my Don’tDestroyOnLoad Managers.</li><li>For a couple frames, these managers prepare themselves. After that, GameStarter object changes the scene and open the game.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*UE5VAhJx1Fn8lhpT7m2L1Q.png" /><figcaption>Starter Scene Hierarchy</figcaption></figure><ul><li>When the new level scene is opened, Don’tDestroyOnLoad Managers from the start scene works with the opened level’s gameobjects in a harmony.</li><li>When the latest level is finished, I opened the new level with <strong>SceneManager</strong>. The persistant managers remain on Don’tDestroyOnLoad. One of the advantage of level based games, you find a break to call <a href="https://docs.unity3d.com/ScriptReference/Resources.html"><strong>Resources</strong></a><strong>.UnloadUnusedAssets()</strong> to unload objects from memory. However, we can still use Addressables to gain more control here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*5zSCJ1g5hQl3pERGpSJwBQ.png" /><figcaption>Example Level Hierarchy</figcaption></figure><h4>3- Prefab Structure</h4><p>Just like inheritance in C#, I strongly recommend using Prefab variants in Unity.</p><blockquote>Please find the link: <a href="https://docs.unity3d.com/Manual/PrefabVariants.html">https://docs.unity3d.com/Manual/PrefabVariants.html</a></blockquote><h4>4- Code Structure</h4><p><strong>4–0 Naming Convention</strong></p><p>Regarding coding, the first thing Devs should agreed on is naming convention in both style and logic. Everything should be clear and in style.</p><blockquote>Please refer to the link for details: <a href="https://unity.com/how-to/naming-and-code-style-tips-c-scripting-unity">https://unity.com/how-to/naming-and-code-style-tips-c-scripting-unity</a></blockquote><p>The one thing I observe that Unreal is better than Unity is naming convention.</p><p><strong>4–1 Programming Paradigms</strong></p><p>Unity finally released Entity-Component system for production. It offers higher performance with tons of GameObjects. However, i think it is still far away from being the first paradigm that comes to our minds. Therefore, most likely we will be using Object-Oriented programming. I will give some real life tips about it.</p><ul><li><strong>Inheritance:</strong> In some cases, Inheritance<strong> </strong>makes us to able to save significant time by avoiding repeating the code.<br>In C#, a class can inherit from only a specific class. However, we can give more functionality with interfaces. If you don’t use them, please use them from now on :)</li><li><strong>Encapsulation: </strong>By encapsulation, other objects may reach but cannot change it. In Unity, we can provide encapsulation easily as seen in the image below. Also, there are other ways to achive it but this is the easiest one for me.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*egQh4azdc4tTykl5-u77HA.png" /></figure><ul><li><strong>Polymorphisim:</strong> As a quick example, please refer to the image below. The first function teleports, the second funtion lerps the position. The only difference is parameter count. This is a basic and common polymorphisim example. Actually polymorphism is more than this one. Please refer to link below.</li></ul><blockquote>More info:<a href="https://www.c-sharpcorner.com/UploadFile/ff2f08/understanding-polymorphism-in-C-Sharp/">https://www.c-sharpcorner.com/UploadFile/ff2f08/understanding-polymorphism-in-C-Sharp/</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*ROk5JQNJKVbUf0FfkY_wqQ.png" /><figcaption>Polymorphism example</figcaption></figure><p><strong>4–2 Core and Systems Architecture</strong></p><p>Split your Runtime code up into 2 pieces “Core” and “Systems”. There are several advantages for that.</p><ul><li>The first reason we will be able to use these “Systems” in every projects without changing it if we fork the repo from base repo. In addition, we can turns them into <strong>Unity Packages</strong>. So, we will be able to use them seperatly in a target Unity project.</li><li>The second reason, we will be able to use different <strong>Assembly Definitions</strong> for systems. Therefore, we do not need to wait for compiling code of the systems when we change the code of the core game system.</li><li>The third, we will be able to test our code easier.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*VNWD9B5Fw2rgFOHnscxg-g.png" /></figure><p><strong>4–3- Design Patterns</strong></p><p>On top of Unity’s design patterns such as <strong>game loop</strong>,<strong> update</strong>, <strong>prototype</strong>(prefab) and <strong>component</strong>, I find useful to implement design patterns below. As I mentioned before, these design patterns are up to your projects needs.</p><ul><li><strong>Observer Pattern: </strong>The observer patterns is simply there is a broadcast object and there are some listener objects. If the broadcast object rises an event, all listeners will be notified.<br>One of the benefits of this desing patterns is that the broadcast object does not care which objects are listening the event. <br>Unlike Unreal, Unity and C# is amazing in observer pattern. In my opinion, it is extreamly powerful and maintainable for large projects. However, please be aware of that you need to unsubscribe listeners when we disable them. Otherwise, memory leaks may occur.<br><br>As a best practice, there should be only one <strong>EventManager</strong> which handles all events in the project. Objects shoud not talk to each other directly for event purposes.<br>Let me give a good example here. “OnGameStateChange” is an event which almost all gameobjects needs to follow. In GameManager, we can trigger this event via EventManager, so all subscribed objects will be notified.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oyZGF7qdaDIign2WTUAkg.png" /><figcaption>Triggering an event as example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*QTGn89yiZCv5ALDj9gFWCg.png" /><figcaption>Listener object as example</figcaption></figure><ul><li><strong>Service-Locator &amp; Singleton Pattern</strong></li></ul><p>Unlike Unreal, Unity is very appropriate for the singleton pattern. We can create a static instance of a class. However, using singleton for many objects cause a complicated situation when projects getting larger. Also, all Devs should be aware of all singletons in the project. This is where service-locator desing patterns comes to solve the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Q5xx_n2W_3OdA8R17a1Nlg.png" /><figcaption>Singleton Design Pattern</figcaption></figure><p>In the service-locator pattern, there is only one singleton object which provides us the other objects we need to reach. Quick and safe way to organize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*eYaw3Vn4TA7AtwtXuhb4uQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*vMEm3ADloLY3IuBO23c9eg.png" /></figure><ul><li><strong>Factory Pattern &amp; Object Pool Pattern</strong></li></ul><p>I am not going to give much info about how to instantiate an object in Unity and Object-Pooling. There are already several videos on youtube. I just want to say that do not create an object in any classes. It will become hard to follow. The planned objects should be created within factories. This is a more maintainable approach.</p><p>I created a simple abstract factory class for my base framework. It gives us an option to get object from Instantiate function or object pool. By the way, I think it would be better to be able to create and return a gameobject from addressables system. (WIP)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*kSYT_ieJIBwCUjX26lp0Mw.png" /></figure><ul><li><strong>Command Pattern &amp; State Machine Pattern<br></strong>Altough I haven’t used them much in my previous projects. I find them very efficent and useful. It is better to check them out.</li></ul><p><strong>4–4 Design Principles</strong></p><ul><li><strong>SOLID:</strong></li></ul><blockquote>Please refer to more info: <a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/may/csharp-best-practices-dangers-of-violating-solid-principles-in-csharp">https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/may/csharp-best-practices-dangers-of-violating-solid-principles-in-csharp</a></blockquote><p>SOLID principles force Devs to write cleaner, more reusable and more maintainable code. I strongly suggest to follow them whenever and wherever you can.</p><p>Let’me quickly share my thoughts on it.</p><p>Single Responsiblity =&gt; Everything should have only one job. Please do not make giant monolith classes, functions etc. I think this is the most important and most applicable one. I take this approach seriously not only in Unity but also in my life :)</p><p>O, L, I, D =&gt; Some best practices are; Do not use switch with enums. Use interfaces instead. These interfaces should cover only specific part, not a monolith one. Objects should be depend on each other with abstractions instead of concreate types.</p><h4>5- CORE</h4><p>The core is the heart of the project. All project-specific codes should be here. I split up into different pieces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*RElq6fZ_LXe-ALZh2Vyg0A.png" /></figure><p><strong>5–1 Gameplay Framework</strong></p><p>When I was reading documantation of Unreal Engine, the gameplay framework seemed to be so different and interesting for me because we are used to write everything ourselves in Unity. <br>If a well-documanted gameplay framework exists in your projects, the framework will lead a boost in efficency. Besides, it prevents some major conflicts between GamePlay Devs. <br>In the light of the infos above, I started to create my own gameplay framework within Unity</p><p><strong>5–1–1 Actors &amp; Characters</strong></p><p>I define the “<strong>Actor</strong>” as gameobject which have specific behaviours. On the other hand, I define “<strong>Character</strong>” as a specific version of actors which inherits from “Actor class”. So, Characters own unique behaviour in addition to Actor’s behaviours. Most gameobject we are going to create will inherit from Actor class and Character class. (This area is still WIP in my framework)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*KxHZBnabW93GG4Tr5DP69A.png" /><figcaption>Some behaviour of Actor objects</figcaption></figure><p><strong>5–2 Managers and Controllers</strong></p><p>Managers are the main responsible objects for all logic in their domain area.</p><ul><li>Most of them have a dependency of a system which provides extra functionality to managers.</li><li>Most of them are DontDestroyedOnload</li><li>Most of them have Controller objects which are responsible for only a specific part of their domain area. So, managers are able to distrubute the responsiblity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*bmWK3t4VFUpEN9MIo0juMQ.png" /><figcaption>Managers</figcaption></figure><p><strong>5–3 Scriptable Objects<br></strong>In my opinion, scriptable objects are one of the most essential part of gamedev in Unity. I think it should be a must for all Devs :)</p><ul><li>Lightweight</li><li>Able to have multiple purposes: storing data, providing logic etc.</li><li>Able to adjust both Core and Systems without touching any component in inspector.</li><li>They can be used/changed/adjust in Editor and Runtime</li><li>Independent from scenes</li><li>Artist and Game Designers will be appriciate you a lot :)</li></ul><h4>6- SYSTEMS</h4><ul><li>Systems are independent from the project’s Core.</li><li>Only a few of them depend of some other system or 3rd party plugins.</li><li>Systems do not need to inherit from MonoBehaviour. They can be pure C# classes. However, I prefer them to be MonoBehaviour which is easier for me to debug on inspector. It is my personel choice :)</li><li>They can be turned into Unity Packages. I plan to convert them in the following versions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*5gI3KURfDAurxsBjwv8M7A.png" /></figure><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d936660df0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity — Scrollable Grid Ui]]></title>
            <link>https://medium.com/@canernurdag/unity-scrollable-grid-ui-e212e37079d8?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e212e37079d8</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[gamedev]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 10:43:01 GMT</pubDate>
            <atom:updated>2022-10-06T10:43:01.374Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unity — Scrollable Grid Ui</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*lLkbIvWBa6TtPFx-.png" /></figure><p>I have just shared an example usage of a <strong>scollable grid ui</strong> in my github. It is very useful for systems such as inventory, shop etc.</p><p>Link: <a href="https://github.com/canernurdag/Unity_ScrollableGridUi">https://github.com/canernurdag/Unity_ScrollableGridUi</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FV-rKY1VbQeo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV-rKY1VbQeo&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/44632bb7454908785b943175ee31f05a/href">https://medium.com/media/44632bb7454908785b943175ee31f05a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e212e37079d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity — Game Architecture with Scriptable Objects]]></title>
            <link>https://medium.com/@canernurdag/unity-game-architecture-with-scriptable-objects-f10ce8b25f50?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f10ce8b25f50</guid>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-architecture]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 10:41:59 GMT</pubDate>
            <atom:updated>2022-10-01T16:12:20.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unity — Game Architecture with Scriptable Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*UHFPGOvOjPw2RRk6" /><figcaption><strong>Source</strong>: <a href="https://unity.com/how-to/architect-game-code-scriptable-objects">https://unity.com/how-to/architect-game-code-scriptable-objects</a></figcaption></figure><p>Scriptable objects are one of the most powerful feature can be used in Unity Engine. In this article, I am going to explain why you should use it as an intermediate object. Let’s dive into.</p><blockquote>Repo: <a href="https://github.com/canernurdag/ScriptableObjectCSharpEventSystem">https://github.com/canernurdag/ScriptableObjectCSharpEventSystem</a></blockquote><h3>Usage 1: Data Container</h3><h4>- Advantages</h4><ul><li>Overcome <strong>thightly-coupled-objects</strong> problem. So, there is no direct dependency between objects.</li><li>Active in all scenes</li><li>Other people, such as game designers, are able to adjust data easily without looking for components on gameobjects/prefabs.</li><li>All data is on place/folder</li><li>Allows us to inherit.</li></ul><h4>- How to create scriptable object for data container</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*Jj1HvBS51K-qX73ONGr8Zw.png" /><figcaption><strong>Abstract Sctiptable Object</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*o0evJAmUrpyjEsbVy1yDqA.png" /><figcaption><strong>Inherited Scriptable object</strong></figcaption></figure><h4>- How to use scriptable objects as data container</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*YkVOwW6zQAryMCLvIn-DoQ.png" /></figure><h4>- How it looks like in Unity Editor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*JD9_XyoNZAaakQ3076c_DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*sEOOdF1TRP8BHdKK3Z4CzA.png" /></figure><h3>Usage 2: Event System (C# Event)</h3><p>On contrast to many unity developer, I prefer to use “<strong>C# event” </strong>system instead of “<strong>UnityEvent</strong>” system. There are two main reasons for that.</p><p>*First one is that <strong>debugging </strong>is more difficult in “UnityEvent” system. <strong>*</strong>Second one is “UnityEvent” system is strongly related to <strong>Unity reflection</strong> system. Therefore I strongly believe that C# event system is more performant. (I have not benchmarked yet.)</p><h4>- Advantages</h4><ul><li>Overcome <strong>thightly-coupled-objects</strong> problem. So, there is no direct dependency between objects.</li><li>Active in all scenes</li><li>Overcome script execution order problem when subscribing/unsubscribing</li><li>Easier to control all events in large projects</li></ul><h4>- How to create scriptable object as event system</h4><ul><li>Create “<strong>EventListener</strong>” and “<strong>EventChannel</strong>” abstract classes.</li><li>Create new <strong>concreate classes with type</strong> from these abstract classes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*6wG-xJRlQnWq5Kko55lc2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*qqJl4lS9A1Qw2Up0dDr-BQ.png" /></figure><h4>- How to use scriptable objects as event system</h4><ul><li>Example of “<strong>OnCharacterHealthChange</strong>” event</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*5aZqqmd06oXBC84vld20pQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*71IdVUzsi5QV2SNyujhrPg.png" /></figure><h4>- How it looks like in Unity Editor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*cWggvSborQGmM0pG4bQ1Tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*asFE9sg2FrEqx-7lo8UtnA.png" /></figure><p>As conclusion, i think scriptable objects are underrated. We should benefit more from it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f10ce8b25f50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity — Implementation of Ui Pointer Image]]></title>
            <link>https://medium.com/@canernurdag/unity-implementation-of-ui-pointer-image-a9a80ba6fe84?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9a80ba6fe84</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Fri, 23 Sep 2022 09:53:39 GMT</pubDate>
            <atom:updated>2022-09-23T09:53:39.820Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unity — Implementation of Ui Pointer Image</h3><p>In mobile games, screen size is not enough to show many things in most cases. Therefore, we sometimes need to inform players about what is going on in outside of screen space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*qbswMp_LcRqz1iPF.png" /></figure><p>“<strong>Ui Pointers</strong>” is one of the most well-known feature at that point. You may find an example implementation in my github which you may find below.</p><p>Please feel free to contact me if you have any questions.</p><h3>Github:</h3><p><a href="https://github.com/canernurdag/UiPointerForGameobject">https://github.com/canernurdag/UiPointerForGameobject</a></p><h3>Youtube:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTB_GocGpwXQ&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTB_GocGpwXQ&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FTB_GocGpwXQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0844c98d090d18539f9664c9bf3ca49/href">https://medium.com/media/e0844c98d090d18539f9664c9bf3ca49/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9a80ba6fe84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of Game Development: Data-Oriented vs Object-Oriented]]></title>
            <link>https://medium.com/@canernurdag/the-future-of-game-development-data-oriented-vs-object-oriented-e92e146dad4c?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e92e146dad4c</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[entity-component-system]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Wed, 14 Sep 2022 11:14:40 GMT</pubDate>
            <atom:updated>2022-09-14T11:14:40.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>I can simply describe game development process as satisfying user and UX needs with<strong> limited resources</strong>.</p><p>In hardware side, there is a non-stop performance and capacity improvement but I guess this will be never enough due to <strong>feature-demand</strong> increase in paralel. So, we need to change something in software side as well.</p><p>In this article I am going to explain<strong> Unity’s DOTS</strong> approach which is more performant as default.</p><p><em>PS: Please check the “memory management in unity” article at first. Otherwise, it would be more difficult to figure out. (</em><a href="https://medium.com/@canernurdag/unity-memory-management-with-pro-tips-860aeec1cb0d"><em>Link</em></a><em>)</em></p><p><em>PS2: I am not going to explain implementation of DOTS in this article. Instead, this article focuses on the logic behind why DOTS is more efficient. Moreover, as of today, the latest version of ECS is 0.51 and it is not stable.</em></p><h3>DOTS <em>(Data-Oriented Tech Stack)</em></h3><p>Let me introduce a new rising star: <strong>DOTS</strong> (<a href="https://unity.com/dots"><em>Link</em></a>)<strong> </strong>from <strong>Unity</strong>, the one of the most widely-used game engine in the world.</p><p>Actually, data-oriented programming has been used in the gaming industry for a while. For example, we can observe it in Blizzard’s Overwatch.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FW3aieHjyNvw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DW3aieHjyNvw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FW3aieHjyNvw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/873cd80cef2daefb8dff0de5524b56ba/href">https://medium.com/media/873cd80cef2daefb8dff0de5524b56ba/href</a></iframe><h3>What is DOTS</h3><p>Unity states that: (<a href="https://learn.unity.com/tutorial/what-is-dots-and-why-is-it-important#5ef9fd90edbc2a3f1c6dcae7"><em>Link</em></a>)</p><blockquote>DOTS is a <strong>combination of technologies</strong> that are new to Unity, which requires a new way of working with Unity and a different approach to thinking about code and data using data-oriented design (DoD), as opposed to the object-oriented approach of Unity without DOTS.</blockquote><p>According to the definition, I would like to say that this is a <strong>paradigma shift</strong> for developers. DOTS completely changes the way developers are familiar.</p><p><strong>DOTS </strong>basicly consists of <strong>3 main sub-systems</strong>: <br>- <em>Entity Component System(ECS), <br>- C# Job System,<br>- Burst Compiler,</em></p><h3>1- Entity Component System (ECS)</h3><p>ECS is an <strong>architectural pattern </strong>that is in the center of DOTS system.</p><p>Basicly, ECS consists of 3 main elements: <strong><em>Entity, Component </em></strong>and<strong><em> System. </em></strong>What a good naming. Isn’t it? :)</p><p>Please refer to image below for a basic example of ECS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYgVTsPKnW76gg_Rq5SCcg.png" /><figcaption>Source: <a href="https://www.youtube.com/watch?v=Z9-WkwdDoNY">https://www.youtube.com/watch?v=Z9-WkwdDoNY</a></figcaption></figure><p>The main purpose of ECS is<strong> transforming “the data” in a more efficient way </strong>by avoiding unnecessary actions.</p><h4><strong>- Entity (Identity)</strong></h4><p>Personally I position “Entity” very close to “GameObject” in my mind. As a more formal definition, Unity states that;</p><blockquote>An entity is essentially an ID. The easiest way to think of it is as a lightweight <a href="https://docs.unity3d.com/Manual/class-GameObject.html">GameObject</a> that does not even have a name by default.<strong>(</strong><a href="https://docs.unity3d.com/Packages/com.unity.entities@0.51/manual/ecs_entities.html">Link</a><strong>)</strong></blockquote><h4><strong>-Component (Data)</strong></h4><p>When we use “<strong>component” </strong>word,<strong> “ECS Component</strong>” can be easily confused with “<strong>Unity Component</strong>” for beginners. Please note that they are completely different.</p><p>As a simple definition, “ECS Component” simply contains data. Unity states that the data can be in form of below ones.</p><blockquote>Usually an instance of a struct (an unmanaged component). Can also be an instance of a class (a managed component) (<a href="https://docs.unity3d.com/Packages/com.unity.entities@0.51/manual/ecs_components.html">Link</a>)</blockquote><p>PS: Due to <strong>structs </strong>are stored in stack memory, mostly we will be using it in ECS.</p><p>Please check the image below. As it can be seen clearly, t<strong>he memory performance increase does not catch the CPU performance increase</strong> in time. This situation makes memory management is more important in terms of performance. Who wants a big bottleneck in project, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*Ix1HtcokTnVkrfQMDbOZhw.png" /><figcaption><a href="https://www.vice.com/en/article/3dkkx8/memory-is-holding-up-the-moores-law-progression-of-processing-power">https://www.vice.com/en/article/3dkkx8/memory-is-holding-up-the-moores-law-progression-of-processing-power</a></figcaption></figure><p>At that point, ECS has a great way to manage memory more efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*8Cn8ynYJ9fqqHIZwOhozMw.png" /><figcaption>Source: <a href="https://www.raywenderlich.com/7630142-entity-component-system-for-unity-getting-started">https://www.raywenderlich.com/7630142-entity-component-system-for-unity-getting-started</a></figcaption></figure><p>The reasons I understand why memory management of ECS is better are;</p><p>1- In OOP, there are several gaps in memory . So, CPU’s cache memory become full with lots of empty space. On contrast, cache memory is more tight in ECS. So, we will be able use more “faster memory”.</p><p><em>PS: Cache memory (L1 and L2) is approx 100 times faster than RAM.</em></p><p>2- When you need a particular data in OOP, you get other not-needed data as well. Let’s give a real life example. Check the image below. We cannot get player’s SpeedMultiplier data without getting “Health” and “PlayerMovement” variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*9SqVcq-_rsI2UKfK7dC9Yg.png" /></figure><p>3- OOP uses “<strong>Array of Structures(AoS)</strong>”, whereas ECS uses “<strong>Structure of Arrays(SoA)</strong>”(<a href="https://www.youtube.com/watch?v=0_Byw9UMn9g"><em>Link</em></a>) (<a href="https://en.wikipedia.org/wiki/AoS_and_SoA"><em>Further info Link</em></a>). SoA has a better and easier data manipulation by <a href="https://en.wikipedia.org/wiki/Single_instruction,_multiple_data"><strong>SIMD instruction</strong></a>. So, we gain a performance here.</p><p>In Unity, ECS handles memory management with “<strong>Archetype</strong>” and “<strong>Chunk</strong>” concepts. So, what are they?</p><p><strong>Archetype </strong>is a “<strong>unique” </strong>combination of component types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*bkvoH5Cca7u-WnkN43t69Q.png" /><figcaption><a href="https://docs.unity3d.com/Packages/com.unity.entities@0.51/manual/ecs_core.html">https://docs.unity3d.com/Packages/com.unity.entities@0.51/manual/ecs_core.html</a></figcaption></figure><p><strong>Chunk </strong>is a block of memory which contains entity and it’s components. Please note that each “Chunk” is represeneted by an “Archetype”.</p><p>Actually, we do not have a direct control here as developers. We can only say “Add” or “Remove” to ECS. Then, ECS handles the memory management automatically. According to the new circumstances, ECS can create a new chunk or destroy a chunk and carry them into another chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*mGCxoSzkKUrFidY2JnBRIg.png" /><figcaption>Source: <a href="https://docs.unity3d.com/Packages/com.unity.entities@0.51/manual/ecs_core.html">https://docs.unity3d.com/Packages/com.unity.entities@0.51/manual/ecs_core.html</a></figcaption></figure><h4><strong>-System (Behavior)</strong></h4><p>The system provides the behavior logic to data. Please note that it transforms only the related data.</p><h3>2- The C# Job System</h3><p>Simply, C# job system allows us to use multithreaded code without any problems such as race condition etc. Obviously, this will give some performance but I would like to see in real life. To be honest, multithreaded coding seems to be complicated and open for some suprising bugs for me. I hope it is worth using it.</p><p>By the way, c# job system has some specific subtypes as “NativeContainer” which is more suitable to work as multithreaded safely. We need to get used to use them as well :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Mg1tc6rRlAHUrPtnl_eaXQ.png" /><figcaption>Source: <a href="https://knowyourmeme.com/photos/1973124-the-glorious-pc-gaming-master-race">https://knowyourmeme.com/photos/1973124-the-glorious-pc-gaming-master-race</a></figcaption></figure><h3>3- The Burst Compiler</h3><p>Burst is a compiler which designed to work perfectly with the Job system. Basicly, it transletes IL code to <strong>optimized </strong>native code. Unity states that burst compiler provides handling jobs as fast and lightweight.</p><p>It looks very easy to use it. It requires only [BurstCompile] attribute.</p><p>For further info:<em> </em><a href="https://docs.unity3d.com/Packages/com.unity.burst@1.7/manual/docs/QuickStart.html"><em>Link</em></a></p><h3>Conclusion</h3><p>If you are seeking for a performance is your game developement process, DOTS is a good tool to be considered.</p><p>In my opinion, OOP will always be with us in game development. However, it may be a good investement to learn DOTS for future.</p><p>Last but not least, please let me know if you face a misleading and/or wrong information. All comments are feedbacks are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e92e146dad4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity — Memory Management  with Pro Tips]]></title>
            <link>https://medium.com/@canernurdag/unity-memory-management-with-pro-tips-860aeec1cb0d?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/860aeec1cb0d</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 08:58:09 GMT</pubDate>
            <atom:updated>2022-09-06T08:58:09.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unity — Memory Management with Pro Tips</h3><p>Optimization has always been an important topic in game development process. As you may heard before, the most well-known optimization areas are CPU, GPU, <strong>memory</strong>, network etc.</p><p>In this article, I am going to explain how memory management works<strong> </strong>on Unity’s game development process and what can be done for better performance.</p><p>Before diving into Unity, let’s check how memory works when programming.</p><p>Operation system creates <strong>abstract version</strong> of physical memory for developers to be able to programe<em>(You can find a simple visual for an example).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*8xiVR9qkVIvEq2_dE-7qbQ.png" /><figcaption>Source: <a href="https://i.stack.imgur.com/oew8U.png">https://i.stack.imgur.com/oew8U.png</a></figcaption></figure><p>In this abstraction, there are some <strong>virtual address spaces (VAS)</strong>. <em>(For further info: </em><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces"><em>Link</em></a><em> )</em></p><p>Two of them should be taken into considiration by Unity developers in order to get better performance: <strong>Heap</strong> and <strong>Stack</strong>.</p><p>Before going deeper into heap and stack, we need to understand which data structures are <strong>value type</strong> and which data structures are <strong>reference type. </strong><em>(Please refer to this link for further info:</em><strong><em> </em></strong><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types"><strong><em>Link1</em></strong></a><strong><em>, </em></strong><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types"><strong><em>Link2</em></strong></a><em>)</em></p><p>Unity states that;</p><blockquote>Types that are stored directly and copied during parameter passing are called value types. These include integers, floats, booleans and Unity’s struct types (eg, <strong>Color</strong> and <strong>Vector3</strong>).</blockquote><blockquote>Types that are allocated on the heap and then accessed via a pointer are called reference types, since the value stored in the variable merely “refers” to the real data. (<a href="https://docs.unity3d.com/560/Documentation/Manual/UnderstandingAutomaticMemoryManagement.html">Link</a>)</blockquote><p>In the light of information given regarding of value type and reference type, now we can compare stack and heap.</p><h3><strong>Stack</strong></h3><ul><li>Store <strong>only value type</strong></li><li>Store “references” of objects that are stored in Heap <em>(This is related to Garbage collection)</em></li><li>Managed by the CPU. Variables are allocated when function is being created and freed when function is finished. This process is done automatically.</li><li>Faster than Heap</li><li>Limited capacity. If the capacity exceeds, stack overflow occurs.</li><li>LIFO structure</li></ul><h3><strong>Heap</strong></h3><ul><li>Store both<strong> reference type</strong> and <strong>value type</strong> (<em>Please note that there is a common wrong information on the internet. Please refer to this link: </em><a href="https://www.youtube.com/watch?v=jONSIhMST9E"><em>Link</em></a>)</li><li>Managed by memory manager or programmer</li><li>Can be fragmented.</li><li>Slower than Stack</li><li>Resizable capacity</li></ul><p>Now, let’s take one more step and learn what is “<strong>garbage</strong>” and what is <strong>Garbage Collection.</strong></p><p><strong>Garbage</strong>: When usage of “reference” which is stored in stack is finished, CPU automatically free the “reference”. However, the object which the “reference” points is still stored in Heap. In this situation, this object is considered as “garbage”.</p><h3>Garbage Collection</h3><p>So, in order to solve this garbage problem, we have garbage collection systems. (<em>For .Net environment’s garbage collection manager please refer to following link. </em><a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/"><em>Link</em></a><em> )</em></p><p>In detail, this manager solves memory allocation and memory release problems for us.<br>According to Microsoft;</p><blockquote>- Memory Allocation</blockquote><blockquote>When you initialize a new process, the runtime reserves a contiguous region of address space for the process. This reserved address space is called the managed heap. The managed heap maintains a pointer to the address where the next object in the heap will be allocated.</blockquote><blockquote>….</blockquote><blockquote>Allocating memory from the managed heap is faster than unmanaged memory allocation..</blockquote><blockquote>-Memory Release</blockquote><blockquote>the garbage collector creates a graph that contains all the objects that are reachable from the roots.</blockquote><blockquote>…</blockquote><blockquote>Objects that are not in the graph are unreachable from the application’s roots. The garbage collector considers unreachable objects garbage and releases the memory allocated for them.</blockquote><p>Until now, we have learnt lots of general things about memory and .NET environment’s memory approach. So, how about in Unity? Let’s analyze Unity’s memory management system now.</p><h3>Unity Memory Management System</h3><p>Unity states that; <a href="https://docs.unity3d.com/Manual/performance-memory-overview.html"><em>(Link)</em></a></p><blockquote>Unity uses three memory management layers to handle memory in your application:</blockquote><blockquote><strong>- Managed memory:</strong> A controlled memory layer that uses a “<strong>managed heap</strong>” and a “<strong>garbage collector(GC)</strong>” to automatically allocate and assign memory.</blockquote><blockquote>Unlike .NET’s GC, this garbage collector is provided by active backend scripting such as Mono, IL2CPP.</blockquote><blockquote><strong>- C# unmanaged memory: </strong>A layer of memory management that you can use in conjunction with the Unity Collections namespace and package. This memory type is called “unmanaged” because it doesn’t use a garbage collector to manage unused parts of memory.</blockquote><blockquote><strong>- Native memory: </strong>C++ memory that Unity uses to run the engine. In most situations, this memory is inaccessible to Unity users, but it’s useful to be aware of it if you want to fine-tune certain aspects of the performance of your application.</blockquote><p>Although this structure seems to be very complicated, don’t worry. It is easier to understand than it looks :)</p><p>At that point, there are two points we need to consider how they work: “Managed heap” and GC at first.</p><p><strong>Managed Heap</strong> is automatically managed by backend scripting runtime. All objects that we create are allocated here. Let’s check the visual below that represent the managed heap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*G5C0NTx4-UxuVwJO.png" /><figcaption>Source: <a href="https://docs.unity3d.com/2020.1/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html">https://docs.unity3d.com/2020.1/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html</a></figcaption></figure><p>As expected, when usage of a data is finished, GC destroys the data from managed heap.</p><p>Due to Unity’s GC algorithm, managed heap is not reordered after deleting a data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*qKOZrpOqh0V-sYM_.png" /><figcaption>Source: <a href="https://docs.unity3d.com/2020.1/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html">https://docs.unity3d.com/2020.1/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html</a></figcaption></figure><p>Sometimes, the upcoming data is bigger than the empty block. So, now we have a problem :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*Npu3EMlB_xG5rhd3.png" /><figcaption>Source: <a href="https://docs.unity3d.com/2020.1/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html">https://docs.unity3d.com/2020.1/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html</a></figcaption></figure><p>In order to solve this problem, managed heap manager has two operations</p><p>1- Run garbage collection process to find an appropriate empty space.</p><p>2- If operation fails, expand the heap size</p><p>As we understand how memory works, it is time to check best practices and examples.</p><h3>Coding Tips</h3><p>1- Use for loop instead of foreach loop<br>2- Reuse List/array wherever possible. Use may use Clear() method before reuse<br>3- Avoid “()=&gt;” Anonymous methods<br>4- Avoid boxing and unboxing wherever possible<br>5- For string manipulation, use StringBuilder<br>6- Cache objects wherever possible<br>7-<strong> Object Pool</strong> for some objects like bullets etc.</p><h3>Unity Tips</h3><p>1- Use “<strong>Addressables System(</strong><a href="https://docs.unity3d.com/Packages/com.unity.addressables@0.3/manual/index.html"><strong><em>Link</em></strong></a><strong>)</strong>” to load and unload objects. There are some reasons for that.</p><p>First of all, everything would be more organized in big projects. You would be able to see what is going on easier.</p><p>Secondly, loading and unloading with “<strong>The Resources</strong>” class (<a href="https://docs.unity3d.com/ScriptReference/Resources.html"><em>Link</em></a>) functions are heavier than you think and expensive. I think “Resources.<a href="https://docs.unity3d.com/ScriptReference/Resources.UnloadUnusedAssets.html">UnloadUnusedAssets</a>()” is not so appropriate for all cases due to not performant. So, this situation leads us to Addressables.</p><p><em>Extra Info: Objcets(such as prefabs) which are referenced on live objects’ components and not instantiated are loaded into memory as well. WTF :)</em></p><p>PS: Addressables has different purposes but i am not going to explain in this article.</p><p><strong>2- Textures</strong> are objects that we need to consider the most in terms of memory.</p><ul><li>Should be compressed</li><li>Size should be “Power of Two”(eg: 256 x 256)</li><li>Use “<strong>Atlas Texture</strong>” : I know artists does not want to spend more time for UV mapping, but this has a huge impace on memory and GPU performance</li></ul><p>PS: Avoid using heavier shaders that have channels you do not use</p><p>As conclusion, memory management is not a point you can miss in game development. I strongly suggest that organize and plan your memory management approach in the beginning of your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=860aeec1cb0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unity — Cinemachine System with Pro Tips]]></title>
            <link>https://medium.com/@canernurdag/unity-cinemachine-system-with-pro-tips-7d5361344c2e?source=rss-624ef0415cc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d5361344c2e</guid>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[cinemachine]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Caner Nurdag]]></dc:creator>
            <pubDate>Thu, 01 Sep 2022 22:26:45 GMT</pubDate>
            <atom:updated>2022-09-02T07:29:51.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unity — Cinemachine System with Pro Tips</h3><p>Today, I am going to explain usage of the cinemachine system in Unity. As I see in several tutorials and topics on the internet, explanations given are not enough due to lack of real-life cases.</p><blockquote>Please note that I am not going to explain all parameters. However, necessary links will be sharing with you for further information.</blockquote><p>First of all, let’s start with the definition. What is the <strong>Cinemachine system</strong>?</p><blockquote><strong>Cinemachine </strong>is one of the best camera management solution in Unity ecosystem. In detail, the cinemachine system is not a replacement for Unity’s camera system. Instead, it <strong>manipulates Unity’s camera system with virtual cameras</strong>.</blockquote><p>In order to add Cinemachine to project, we will be using “<strong><em>Package Manager</em></strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*V25xCJAuwTUOL0eTO730-w.png" /></figure><p>After importing the Cinemachine package, a new section named as “Cinemachine” will be created in the header area. There are plenty Camera types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Q5cQvND3lOzvGXk4vMFtSg.png" /></figure><p><strong>“Virtual Camera” </strong>is the first core concept to be understood at that point. Now, we are able to manipulate “<strong>Main Camera</strong>” with this “Virtual camera”. Please be aware of that changing transform of “Main Camera” is not possible from now on. “Main Camera”s position and rotation adjustments can be made via “Virtual Camera” parameters. Please check the links below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*jNsL3177WeEzFOZ_oioiSA.png" /></figure><blockquote><strong>Virtual Camera Documantation:</strong> <a href="https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineVirtualCamera.html">https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineVirtualCamera.html</a></blockquote><blockquote><strong>Youtube Tutorial:</strong> <a href="https://www.youtube.com/watch?v=asruvbmUyw8">https://www.youtube.com/watch?v=asruvbmUyw8</a></blockquote><p><strong>Tip0: </strong>Do not set your target object’s Transform to Follow and LookAt direcly. Instead please use a ghost object. There are some reasons for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*MAmI27NwsFNpk4E_GPRMRA.png" /></figure><ul><li>When set a new Transform in runtime, virtual camera teleport immediately. There is no way to blend to the new position. So, lerping position of ghost object to new position may be solution here. Please check the function below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*XPccJGjsLVNaUFafY8yB2w.png" /></figure><ul><li>It is not possible to fixed Camera’s position for an axis. So, fixing ghost object position for an axis in a different class may be solution here.</li><li>Rotation of real target cause some undesired changes in virtual camera. Using ghost object solve this problem faster and easier.</li></ul><p><strong>Tip1:</strong> In order to reach and change parameters in Virtual Camera may require “GetCinemachineComponent”. Please check two example functions below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*VwAMFvp4p7r8foVLBd16yQ.png" /></figure><p><strong>Tip2: </strong>It is possible to use virtual camera for camera shaking. Please refer to this link: <a href="https://www.youtube.com/watch?v=ACf1I27I6Tk">https://www.youtube.com/watch?v=ACf1I27I6Tk</a></p><p><strong>Tip3: </strong>“<strong>Cinemachine Extenstion</strong>” is a way to give ability to virtual camera. However, due to lack of good documantation, I have not used it a lot. Instead, I use ghost object method.</p><p>So, it is time to manage a group of virtual cameras. At that point, there are several options. According to your needs and purpose, you can choose one of them. Sometimes, these options can be used in place of each other to achieve the same goal. In this article, I would like to mention about State-Driven camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*yuX5ob1fJDH_D6E8rrvOYQ.png" /></figure><p>Link: <a href="https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineManagerCameras.html">https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/manual/CinemachineManagerCameras.html</a></p><p><strong>Tip4:</strong> Please do not use changing <strong>VirtualCameraGameobject </strong>activeness to manage virtual camera groups. You can easily get lost.</p><p>Within these manager cameras,<strong> State-Driven Camera </strong>shining like star :) <br>Basicly, “State-Driven Camera” blending virtual cameras according to a state system. It is a good way to change active virtual camera and keep everything under control, even in big projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*tSZZ9z6nbp_3bGuy5mLV3w.png" /></figure><blockquote><strong>State-Driven Camera Documantation:</strong> <a href="https://docs.unity3d.com/Packages/com.unity.cinemachine@2.2/manual/CinemachineStateDrivenCamera.html">https://docs.unity3d.com/Packages/com.unity.cinemachine@2.2/manual/CinemachineStateDrivenCamera.html</a></blockquote><blockquote><strong>Youtube Tutorial:</strong> <a href="https://www.youtube.com/watch?v=2X00qXErxIM">https://www.youtube.com/watch?v=2X00qXErxIM</a></blockquote><p><strong>Tip5: </strong>The key point of using State-Driven camera is using Unity’s animator system. Changing animation state leads to change the active virtual camera. I wish something better would exist to control states instead of animator. Hear me Unity :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*-mGgURhMiIlsNQSTjyDw5g.png" /></figure><p>As<strong> conclusion</strong>, the cinemachine system is amazing for fast and easy camera controls in games. I strongly believe that all Unity developers should use it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d5361344c2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>