启用和禁用组件

启用和禁用组件

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); // 销毁当前游戏对象
    }
}
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐