unity gameobject setactive
时间: 2023-12-22 08:05:39 浏览: 76
Unity's SetActive function is a method that can be used to enable or disable a GameObject in your game. The GameObject is the basic object in Unity that represents any object in a scene. When a GameObject is disabled, it means that it is not rendered, updated or processed by the game engine.
Here's an example of how to use the SetActive function:
```
public GameObject myGameObject;
void Start()
{
// Disable the GameObject
myGameObject.SetActive(false);
}
void Update()
{
// Enable the GameObject when the player presses the spacebar
if (Input.GetKeyDown(KeyCode.Space))
{
myGameObject.SetActive(true);
}
}
```
In this example, we first declare a reference to our GameObject using the public keyword. This makes the GameObject accessible from the Unity editor, allowing us to drag and drop the object into the script's public field.
In the Start function, we use the SetActive method to disable the GameObject by passing in the value false.
In the Update function, we check if the player has pressed the spacebar using the Input.GetKeyDown method. If the spacebar is pressed, we use the SetActive method to enable the GameObject by passing in the value true.
By using the SetActive method, we can easily enable or disable GameObjects in our game as needed.
阅读全文