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

时间:2019-06-06 19:11:16

标签: c# unity3d collider

在进行类似小行星的游戏时,当我的飞船被击中时,它会炸毁,我实例化一艘新飞船并用盾牌围住它几秒钟。当船被盾牌包围时,我禁用碰撞几秒钟。所有这一切。几秒钟后,我隐藏了盾牌(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;

    }

1 个答案:

答案 0 :(得分:2)

调用Instantiate(player);时,您正在创建一个与上一个播放器对象完全独立的对象。实例化播放器对象时,需要重新分配playerCollider来引用新创建的对象上的对撞机。

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

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);
}