为什么 collider.enable = true 在我的代码中不起作用?

Why is collider.enable = true not working in my code?

在类似小行星的游戏中工作,当我的船被击中时它爆炸了,我实例化了一艘新船并用盾牌包围它几秒钟。当船被护盾包围时,我禁用碰撞几秒钟。这一切都有效。几秒钟后,我隐藏屏蔽 (SetActive(false)),然后设置 playerCollider.enabled = true。盾牌隐藏但碰撞器不会重新启用。

被杀时的代码

 public void KilledWaitTime()
    {
        SetLivesText();
        Instantiate(player); //respawns player after killed
        shield.SetActive(true);
        playerCollider.enabled = false; //disables collider while shield up.
        Debug.Log("collider = " + playerCollider.name);
        Debug.Log("player = " + player.name);
        Invoke("RemoveShields", 3);
    }

用于移除防护罩并重新启用对撞机的代码

 public void RemoveShields()
    {
        shield.SetActive(false);
       // Collider pc = player.GetComponent<Collider>();
        Debug.Log("collider pc = " + playerCollider.name);
        Debug.Log("player pc = " + player.name);
        playerCollider.enabled = true;

    }

当您调用 Instantiate(player); 时,您正在创建一个与之前的播放器对象完全不同的对象。实例化player对象时,需要re-assignplayerCollider引用新建对象上的collider

您可能还希望将播放器预制件和当前播放器对象分开:

private GameObject playerPrefab;
private GameObject player;

public void KilledWaitTime()
{
    SetLivesText();
    player = Instantiate(playerPrefab); //respawns player after killed
    playerCollider = player.GetComponent<Collider>();

    shield.SetActive(true);
    playerCollider.enabled = false; //disables collider while shield up.
    Debug.Log("collider = " + playerCollider.name);
    Debug.Log("player = " + player.name);
    Invoke("RemoveShields", 3);
}