How to use Action event in by C# script in unity

An action is a function by using various events like user input, collisions, or custom timers. We can use functions as actions and then it can be called at appropriate event or trigger in unity. An example of using action function in unity is given below:

1. Create a new C# script.

2. Enter name of script whatever you want and then open it in visual studio.

3. Create a new function in this script which we want to use as an action. For example:

Code :
public void MyAction()
{
    Debug.Log("My action event is triggered!");
}

4. Now add this script to a GameObject in scene.

5. We can use any appropriate event for calling of this function. For example, we use OnMouseDown() event to call this function when user click on the object:

Code :
void OnMouseDown()
{
    MyAction();
}

6. Now when we play this scene we will see the message "My action was triggered!" log in console when we click on object.


We can also use other events for triggering action function, like Update(), Start(), OnTriggerEnter(), OnCollisionEnter(), OnEnable(), etc. We can also pass parameters into function for making it more versatile. For example:

Code :
public void MyAction(int value)
{
    Debug.Log("My action is triggered with a value: " + value);
}

Then we can call this function with a specific value.

Code :
void OnMouseDown()
{
    MyAction(5);
}
actions in unity


We can also create a more flexible and robust system by using delegates and events in unity for handling actions. We can define a type of function by using delegates and then we can assign many methods to that type so when delegate is invoked all method assigned with it are called. Events are C# built-in features which allow us to create delegates and to raise a event when certain conditions are met. An example of using events in unity  is given below:

Code :
using UnityEngine;
using System;

public class MyScript : MonoBehaviour
{
    public event Action OnMyEvent;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (OnMyEvent != null)
            {
                OnMyEvent();
            }
        }
    }
}

This script defined an event called OnMyEvent of type Action where Action is a delegate without any parameters. This script check for user input in Update() method and if user press space key and then if event is not null, it will call OnMyEvent() function. If we want to use this event from other script, we just need to assign a method to the event like below example:

Code :
void Start()
{
    MyScript myScript = GetComponent<MyScript>();
    myScript.OnMyEvent += MyAction;
}

MyAction() method will be called whenever OnMyEvent event is reaised in MyScript.


Comments