Unity(六):组件的启用禁用enabled、游戏对象激活SetActive、销毁Destroy
启用和禁用组件public class EnableComponents : MonoBehaviour{private Light light;private void Start(){light = GetComponent<Light>();}private void Update(){if(Input.GetKeyDown(KeyCode.Space))li
·
启用和禁用组件
public class EnableComponents : MonoBehaviour
{
private Light light;
private void Start()
{
light = GetComponent<Light>();
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
light.enabled = !light.enabled;
}
}
激活游戏对象,游戏对象的激活状态
SetActive([Boolean])
activeInHierarchy
:父对象的激活状态不会影响子游戏对象的激活状态activeSelf
:显示父对象的激活状态
public class ActiveObjects : MonoBehaviour
{
public GameObject cube, sphere;
private Boolean isActive;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
cube.SetActive(isActive);
isActive = !isActive;
// False
Debug.Log("Cube activeSelf 父游戏对象 -> " + cube.activeSelf);
// False
Debug.Log("Cube activeInHierarchy 父游戏对象 -> " + cube.activeInHierarchy);
// True
Debug.Log("Sphere activeSelf 子游戏对象 -> " + sphere.activeSelf);
// False
Debug.Log("Sphere activeInHierarchy 子游戏对象 -> " + sphere.activeInHierarchy);
}
}
}
销毁Destroy
public class DestroyObjectOrComponent : MonoBehaviour
{
private BoxCollider boxCollider;
void Start()
{
// 获取当前游戏对象的盒状碰撞器组件
boxCollider = GetComponent<BoxCollider>();
}
void Update()
{
if (Input.GetKey(KeyCode.C))
Destroy(boxCollider, 2f); // 2秒后销毁组件
if (Input.GetKey(KeyCode.O))
Destroy(this.gameObject); // 销毁当前游戏对象
}
}
更多推荐
所有评论(0)