value | 激活或停用对象:true 可激活 GameObject,而 false 可停用 GameObject。 |
根据给定的值 true
或 /false/,激活/停用 GameObject。
GameObject 可能因为父项未处于活动状态而处于非活动状态。在这种情况下,调用 SetActive 不会激活它,而是仅设置此 GameObject 的本地状态,该状态可使用 GameObject.activeSelf 加以检查。当所有父项均处于活动状态时,Unity 便可以使用此状态。
停用 GameObject 将禁用每个组件,包括附加的渲染器、碰撞体、刚体和脚本。例如,Unity 将不再调用附加到已停用 GameObject 的脚本的 Update()
方法。当 GameObject 收到 SetActive(true)
或 SetActive(false)
时,将调用 OnEnable
或 /OnDisable/。
using UnityEngine;
// GameObject.SetActive demo. // // Show a column of cubes. Any cube can be clicked by the mouse // and have SetActive set to false. The cubes beneath the hidden // cube will not have SetActive set to false, but will not be // shown. This is the feature of SetActive. Also, the cubes have // SetActive set back to true 2 seconds after they are hidden.
public class Example : MonoBehaviour { private GameObject[] gameObjects; private int numberOfGameObjects = 5; private float delay = 2.0f;
void Awake() { // Create some GameObjects. gameObjects = new GameObject[numberOfGameObjects];
for (int i = 0; i < numberOfGameObjects; i++) { // Create, place in the world, and set name. gameObjects[i] = GameObject.CreatePrimitive(PrimitiveType.Cube); gameObjects[i].transform.position = new Vector3(0.0f, -1.5f * i, 0.0f); gameObjects[i].name = i.ToString();
// The first GameObject is the top parent, so ignore it for now. if (i > 0) { gameObjects[i].transform.parent = gameObjects[i - 1].transform; } } }
private float startTime = 0.0f; private bool increaseTime = false;
void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
// Set GameObject SetActive to false when // hit by a mouse click. if (hit) { hitInfo.transform.gameObject.SetActive(false);
startTime = 0.0f; increaseTime = true; } }
// Show the GameObjects when time exceeds delay. if (increaseTime) { startTime += Time.deltaTime; if (startTime > delay) { for (int i = 0; i < numberOfGameObjects; i++) { // Note that some of the GameObjects // might have true already. gameObjects[i].SetActive(true); }
increaseTime = false; } } }
// Show time. void OnGUI() { GUIStyle fontSize = new GUIStyle(GUI.skin.GetStyle("label")); fontSize.fontSize = 24; GUI.Label(new Rect(10, 10, 250, 50), "Time: " + startTime.ToString("F2"), fontSize); } }