Reducing the number of objects by destroying objects at death a time

Optimization principal 1: Minimize the number of active and enabled objects in a scene.

One way to reduce the number of active objects is to destroy objects when they are no longer needed. As soon as an object is no longer needed, we should destroy it; this saves both memory and processing resources since Unity no longer needs to send the object such messages as Update() and FixedUpdate(), or consider object collisions or physics and so on.

However, there may be times when we wish not to destroy an object immediately, but at some known point in the future. Examples might include after a sound has finished playing (see that recipe Waiting for audio to finish before auto-destructing object in Chapter 9, Playing and Manipulating Sounds), the player only has a certain time to collect a bonus object before it disappears, or perhaps an object displaying a message to the player should disappear after a certain time.

This recipe demonstrates how objects can be told to start dying, and then to automatically destroy them after a given delay has passed.

Reducing the number of objects by destroying objects at death a time

How to do it...

To destroy objects after a specified time, follow these steps:

  1. Create a new 2D project.
  2. Create a UI Button named Click Me, and make it stretch to fill the entire window.
  3. In the Inspector, set the Button's Text child to have left-aligned and large text.
  4. Add the following script class DeathTimeExample.cs to Button Click Me:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class DeathTimeExample : MonoBehaviour {
      public void BUTTON_ACTION_StartDying() {
        deathTime = Time.time + deathDelay;
      }
    
      public float deathDelay = 4f;
      private float deathTime = -1;
    
      public Text buttonText;
    
      void Update(){
        if(deathTime > 0){
          UpdateTimeDisplay();
          CheckDeath();
        }
      }
    
      private void UpdateTimeDisplay(){
        float timeLeft = deathTime - Time.time;
        string timeMessage = "time left: " + timeLeft;
        buttonText.text = timeMessage;
      }
    
      private void CheckDeath(){
        if(Time.time > deathTime) Destroy( gameObject );
      }
    }
  5. Drag the Text child of Button Click Me into the script's public variable Button Text, so this script is able to change the button text to show the countdown.
  6. With Button Click Me selected in the Hierarchy, add a new On Click() event for this button, dragging the button itself as the target GameObject and selecting public function BUTTON_ACTION_StartDying(),as shown in the following screenshot:
    How to do it...
  7. Now, run the scene; once the button is clicked, the button's text should show the countdown. Once the countdown gets to zero, Button Click Me will be destroyed (including all its children, in this case, just the GameObject Text).

How it works...

The float variable deathDelay stores the number of seconds the object waits before destroying itself once the decision has been made for the object to start dying. The float variable deathTime either has a value of -1 (no death time yet set) or it is a non-negative value, which is the time we wish the object to destroy itself.

When the button is clicked, the BUTTON_ACTION_StartDying() method is called. This method sets this deathTime variable to the current time plus whatever value is set in deathDelay. This new value for deathTime will be a positive number, meaning the IF-statement in the Update() method will fire from this point onward.

Every frame method Update() checks if deathTime is greater than zero (that is, a death time has been set), and, if so, it then calls, the UpdateTimeDisplay() and CheckDeath() methods.

The UpdateTimeDisplay() methods creates a string message stating how many seconds are left and updates the Button Text to show this message.

The CheckDeath() method tests whether the current time has passed the deathTime. If the death time has passed, then the parent gameObject is immediately destroyed.

When you run the scene, you'll see the Button removed from the Hierarchy once its death time has been reached.

See also

Refer to the following recipes in this chapter for more information:

  • Reducing the number of enabled objects by disabling objects whenever possible
  • Reducing the number of active objects by making objects inactive whenever possible
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.108.175