Optimization principal 1: Minimize the number of active and enabled objects in a scene.
Sometimes, we may not want to completely remove an object, but it is possible to go one step further than disabling a scripted component by making the parent GameObject
that contains the scripted component inactive
. This is just like deselecting the checkbox next to the GameObject
in the Inspector, as shown in the following screenshot:
To reduce computer processing workload requirements by making an object inactive when it becomes invisible, follow these steps:
DisableWhenNotVisible
from your Cube, and instead, add the following C# script class InactiveWhenNotVisible
to Cube:using UnityEngine; using System.Collections; using UnityEngine.UI; public class InactiveWhenNotVisible : MonoBehaviour { // button action public void BUTTON_ACTION_MakeActive(){ gameObject.SetActive(true); makeActiveAgainButton.SetActive(false); } public GameObject makeActiveAgainButton; private GameObject player; void Start(){ player = GameObject.FindGameObjectWithTag("Player"); } void OnBecameInvisible() { makeActiveAgainButton.SetActive(true); print ("cube became invisible"); gameObject.SetActive(false); } void Update(){ float d = Vector3.Distance( transform.position, player.transform.position); print(Time.time + ": distance from player to cube = " + d); } }
Make Cube Active Again
, and position the button so that it is at the top of the Game panel and stretches the entire width of the Game panel, as shown in the following screenshot:BUTTON_ACTION_makeCubeActiveAgain()
.MakeActiveAgainButton
variable slot of its script class InactiveWhenNotVisible
component, as shown in the following screenshot:Initially, the Cube is visible and the Button is inactive (so not visible to the user). When the Cube receives an OnBecameInvisible
event message, its OnBecameInvisible()
method will execute. This method performs two actions:
When the Button is clicked, it makes the Cube object active again and makes the Button inactive again. So, at any one time, only one of the Cube and Button objects are active, and each makes itself inactive when the other is active.
Note that an inactive GameObject
does not receive any messages, so it will not receive the OnBecameVisible()
message, and this may not be appropriate for every object that is out of sight of the camera. However, when deactivating objects is appropriate, a larger performance saving is made compared to simply disabling a single scripted Monobehaviour
component of a GameObject
.
The only way to reactivate an inactive object is for another object to set the GameObject
component's active property back to true
. In this recipe, it is the Button
GameObject, which, when clicked, runs the BUTTON_ACTION_makeCubeActiveAgain()
method, which allows our game to make the Cube active again.
3.135.202.203