在Unity中启用/禁用预制组件

时间:2019-05-13 17:12:12

标签: c# unity3d

正如您在脚本中看到的那样,在销毁功能上,我正在禁用预制组件,它在游戏过程中进展顺利,但是在停止游戏后,它仍然保持禁用状态,我知道原因是它是预制的,因此可以保存该信息但是如何仅在玩游戏时才能禁用它?我考虑过while循环,但它崩溃了,还有Awake函数。有什么想法吗?

private void OnDestroy()
{
    Lose = true;
    ENEMIES.GetComponent<EnemiesMovement>().unit = 0.0f;
    prefenBullet.GetComponent<MeshRenderer>().enabled = false;
    prefenBullet.GetComponent<BoxCollider2D>().enabled = false;
}

1 个答案:

答案 0 :(得分:2)

将实例保存在GameObject变量中,以便稍后可以在代码中访问和修改。像这样:

// Reference to the Prefab. Drag a Prefab into this field in the Inspector.
public GameObject myPrefab;
GameObject myPrefabInstance;

    // This script will simply instantiate the Prefab when the game starts.
void Start()
{
    // Instantiate at position (0, 0, 0) and zero rotation.
    myPrefabInstance = Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
}

private void OnDestroy()
{
    myPrefabInstance.GetComponent<MeshRenderer>().enabled = false;
    myPrefabInstance.GetComponent<BoxCollider2D>().enabled = false;
}