Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
News - Blog: How to use C# Events in Unity

#1
Blog: How to use C# Events in Unity

<div style="margin: 5px 5% 10px 5%;"><img src="http://www.sickgaming.net/blog/wp-content/uploads/2018/07/blog-how-to-use-c-events-in-unity.jpg" width="1121" height="237" title="" alt="" /></div><div><p><strong><i><small> The following blog post, unless otherwise noted, was written by a member of Gamasutra’s community.<br />The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company. </small></i></strong> </p>
<hr />
<h2>Objective</h2>
<p>The main objective of this blog post is to give you an idea about how to use C# Events in Unity.</p>
<p><strong>What is problem with Delegates?</strong></p>
<p><strong>What is an Event?</strong></p>
<p><strong>Why Events are used?</strong></p>
<p><strong>How to declare an Event?</strong></p>
<p><em>You may have all these questions in your mind.</em></p>
<p><em>Don’t worry, you are at the right place.</em></p>
<p><strong>Let’s start, Do you remember the problem of Delegates?</strong></p>
<p><em>If we use a single delegate after the use of multicast delegates then it will reset the existing invocation list. </em></p>
<p><em>This situation is very difficult to track if multiple classes subscribe to the same delegate.</em></p>
<p><em>This is the reason why we have Events.</em></p>
<p><em>Let’s see how they work.</em></p>
<p>Events are a type of special delegates which are used when you want to notify other classes when something happens. Like, on <strong>GameStart</strong>, on <strong>Gameover</strong>.</p>
<p><strong>Let’s take a look on declaration and use of an Events.</strong></p>
<p><strong>1. Declare a Delegate</strong></p>
<pre><code>public delegate void OnGameStart();</code></pre>
<p><strong>2.Create an Event</strong></p>
<pre><code>public static event OnGameStart onGameStart;</code></pre>
<p><strong>3. Point to method</strong></p>
<pre><code>onGameStart += Move;</code></pre>
<p><strong>4. Invoke an Event</strong></p>
<pre><code>onGameStart ();</code></pre>
<p><strong>Let’s, create a simple game using Event Delegate.</strong></p>
<p><strong>Step 1</strong></p>
<ul>
<li>Create an empty <strong>GameObject </strong>name it as you like.</li>
<p>
</ul>
<p><strong>Step 2</strong></p>
<ul>
<li>Create C# script name it <strong>EventManager</strong>.</li>
<p>
</ul>
<p>Write following code in <strong>EventManager.cs</strong></p>
<pre><code>public class EventManager : MonoBehaviour { public delegate void OnButtonClick(); public static event OnButtonClick onButtonClick; public void RaiseOnButtonClick() { if (onButtonClick != null) { onButtonClick(); } } }</code></pre>
<p><strong>Step 3</strong></p>
<ul>
<li>Assign it to an empty <strong>GameObject</strong>.</li>
<p>
</ul>
<p><strong>Step 4</strong></p>
<ul>
<li>Create a 2d object and assign knob as sprite in <strong>SpriteRenderer</strong>.</li>
<p>
</ul>
<p><strong>Step 5</strong></p>
<ul>
<li>Create  C# script name <strong>PlayerTransformAndColor.</strong></li>
<p>
</ul>
<p>Write following code in <strong>PlayerTransformAndColor.cs</strong></p>
<pre><code>public class PlayerTransformAndColor : MonoBehaviour { public SpriteRenderer spriteRenderer; public Color color1, color2; private void OnEnable() { EventManager.onButtonClick += ChangePosition; EventManager.onButtonClick += ChangeColor; } public void ChangePosition() { transform.position += Vector3.one * 2; } public void ChangeColor() { spriteRenderer.color = color2; } }</code></pre>
<p><strong>Step 6</strong></p>
<ul>
<li>Assign it to empty <strong>GameObject</strong>.</li>
<p>
</ul>
<p>Now let’s do some changes in <strong>PlayerTransformAndColor.cs</strong></p>
<pre><code>public class PlayerTransformAndColor : MonoBehaviour { public SpriteRenderer spriteRenderer; public Color color1, color2; private void OnEnable() { EventManager.onButtonClick += ChangePosition; EventManager.onButtonClick += ChangeColor; EventManager.onButtonClick = ChangeRotation; } public void ChangePosition() { transform.position += Vector3.one * 2; } public void ChangeColor() { spriteRenderer.color = color2; } public void ChangeRotation() { transform.Rotate(0, 90, 0); } }</code></pre>
<p>You may find the error. Like shown in below,</p>
<p><img alt="error" src="http://www.sickgaming.net/blog/wp-content/uploads/2018/07/blog-how-to-use-c-events-in-unity.jpg" /></p>
<p><strong>Got the  idea, How Events overcome the problem of Delegates.??</strong></p>
<p>Events adds a layer of abstraction and protection on delegate, this protection prevents client of the delegate from resetting the delegate and invocation list.  </p>
<p>Now let’s take one more practical example. That gives you more clear idea about how event handle multiple event listeners by only one event Invocation.</p>
<p><strong>For this, we’ll follow these steps.</strong></p>
<p><strong>Step 1</strong></p>
<ul>
<li>Create an empty GameObject name it <strong>EventManager</strong>.</li>
<p>
</ul>
<p><strong>Step 2</strong></p>
<ul>
<li>Create C# scrip and name it <strong>Eventmanager</strong>.</li>
<p>
</ul>
<p>Write following code in <strong>EventManager.cs</strong></p>
<pre><code>public class EventManager : MonoBehaviour { public delegate void OnRest(); //Declare a Delegate public static event OnRest onReset; //Create an Event public delegate void OnReStart(); //Declare a Delegate public static event OnReStart onReStart; //Create an Event public static void RaiseOnReset() { if (onReset != null) { onReset(); //Invoke an Event } } public static void RaiseOnReStart() { if (onReStart != null) { onReStart(); //Invoke an Event } }
}</code></pre>
<p><strong>Step 3</strong></p>
<ul>
<li>Assign it to an empty <strong>GameObject(EventManager)</strong>.</li>
<p>
</ul>
<p><strong>Step 4</strong></p>
<ul>
<li>Create an empty <strong>GameObject</strong> name it <strong>EventHandler</strong>.</li>
<p>
</ul>
<p><strong>Step 5</strong></p>
<ul>
<li>Create C# script name it <strong>EventHandler</strong></li>
<p>
</ul>
<p>Write following code in <strong>EventHandler.cs</strong></p>
<pre><code>public class EventHandler : MonoBehaviour
{ void Update() { if (Input.GetKeyDown(KeyCode.P)) { EventManager.RaiseOnReset(); // Function call to invoke an Event } else if (Input.GetKeyDown(KeyCode.S)) { EventManager.RaiseOnReStart(); // Function call to invoke an Event } }
}</code></pre>
<p><strong>Step 6</strong></p>
<ul>
<li>Assign it to an empty <strong>Gameobject(EventHandler)</strong>.</li>
<p>
</ul>
<p><strong>Step 7</strong></p>
<p>Create a 3D game <strong>object(Cube)</strong>.</p>
<p><strong>Step 8</strong></p>
<ul>
<li>Create C# script name it <strong>ObjectMotion</strong>.</li>
<p>
</ul>
<p>Write following code in <strong>ObjectMotion.cs</strong></p>
<pre><code> public class ObjectMotion : MonoBehaviour { private float minRange, maxRange; private float speed, restartSpeed; private Vector3 newPosition; private void OnEnable() { EventManager.onReset += Reset; EventManager.onReStart += Restart; } void Start() { minRange = 1; maxRange = 3; speed = Random.Range(minRange, maxRange); restartSpeed = speed; } void Update() { newPosition = transform.position; newPosition.x = Mathf.Sin(Time.time) * speed; transform.position = newPosition; } private void OnDisable() { EventManager.onReset -= Reset; EventManager.onReStart -= Restart; } public void Reset() { speed = 0; } public void Restart() { speed = restartSpeed; } }</code></pre>
<p><strong>Step 9</strong></p>
<ul>
<li>Assign it to 3D <strong>GameObject(Cube)</strong>.</li>
<p>
</ul>
<p><em>Now create multiple copies of 3D GameObject.</em></p>
<p><em>Run Unity, and press “P” to reset the position and “S” to restart the motion.</em></p>
<p>From the above examples we may come to the  following conclusion,</p>
<div class="border-box">
<h3 class="heading-medium"><span class="box">Conclusion</span></h3>
<ul>
<li>Delegates and Events help us to write modular and reusable code.</li>
<p> </p>
<li>Always use Events together with Delegates for safety.</li>
<p> </p>
<li>Do not forget to unsubscribe otherwise, it will lead to memory leak.</li>
<p>
</ul>
</div>
<p><em>Feel free to contact us if you really liked this blog. And don’t forget to share your comments below!</em></p>
</div>
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016