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:
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:
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:
Then we can call this function with a specific value.
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:
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:
MyAction() method will be called whenever OnMyEvent event is reaised in MyScript.
Comments
Post a Comment