📅  最后修改于: 2023-12-03 15:35:29.337000             🧑  作者: Mango
Deactivating objects in Unity can be done easily from the editor, but sometimes one needs to do it from code. Here is a guide on how to achieve this using C#.
The easiest way to deactivate an object from code is by using the SetActive method of the GameObject class. This method takes a boolean argument to activate or deactivate the object.
public GameObject objectToDeactivate;
void DeactivateObject()
{
objectToDeactivate.SetActive(false);
}
In the above code snippet, the objectToDeactivate GameObject is deactivated by setting its active state to false. This can be called whenever the object needs to be deactivated.
For components such as scripts, the SetActive method doesn't work. Instead, we need to use the enabled property of the component. This property is used to enable or disable the script/component.
public MonoBehaviour scriptToDeactivate;
void DeactivateScript()
{
scriptToDeactivate.enabled = false;
}
In the above code snippet, the scriptToDeactivate MonoBehaviour is deactivated by setting its enabled property to false. This can be called whenever the script needs to be deactivated.
In summary, deactivating objects and scripts is a very useful feature in Unity. It can be done easily from code by using the SetActive method for GameObjects and the enabled property for components/scripts.