Advanced Concepts
Learn the advanced concepts of scripting in Unity.
We'll cover the following...
Unity provides tools and workflows tailored to game development, such as a visual editor for creating GameObjects and scenes, physics simulations, and support for various platforms. Additionally, Unity uses a component-based system for GameObject behavior. Unlike traditional inheritance-based systems used in other frameworks, each GameObject can have multiple components that define its behavior. Now, we’ll cover some other ideas that will aid us in developing a holistic game.
Multi-frame tasks
The lifespan of an event handler begins with the event’s invocation and ends when the method returns. Therefore, the lifespan of the handler is bound by the next frame to be rendered. However, some tasks demand that the execution of the method should persist across the frame.
Let’s say that we have a method that iteratively increases the size of a GameObject:
void Enlarge() {for (float i = 1f; i <= 10f; i += 0.1f) {transform.localScale = new Vector3(i, i, i);}}
If we execute this function in the Start
method, we’ll notice that the GameObject size just increases from 1
to 10
in an instant:
As a work-around, we could leverage the Update
method and simply enlarge the GameObject on a frame-by-frame basis:
void Update() {if (transform.localScale.x < 10f)transform.localScale = new Vector3(transform.localScale.x + 0.1f,transform.localScale.y + 0.1f,transform.localScale.z + 0.1f,);}
However, a much cleaner way to achieve this is to use a coroutine. ...