【问题标题】:Collider2d not working when game restarted after player die玩家死亡后重新启动游戏时,Collider2d 无法正常工作
【发布时间】:2021-06-29 16:49:18
【问题描述】:

我已经检查了游戏中的重启按钮,它的作用就像一个护身符,玩家仍然会因碰撞障碍物而受到伤害,但是当玩家死亡并按下重启按钮时,玩家不会与任何障碍物发生碰撞,

所以我认为这是因为我的“虚空死亡”,但我只禁用了一些,当我重新启动游戏时它仍然有效,只是玩家不会与任何障碍物发生碰撞,只是......帮助我!

public void Die() {
    //Disable Score
    ScoreCounter.SetActive(false);

    //Animation
    AN.Play("Death");

    //Stop Coroutine
    StopCoroutine("Invulnerability");

    //Load Restart Menu
    PanelRestart.SetActive(true);

    //Disable Object Function
    GetComponent<CapsuleCollider2D>().enabled = false;
    this.enabled = false;
}

这是我的暂停按钮脚本,我在游戏中使用了这个暂停按钮然后重新启动,当玩家死亡然后重新启动

public void RestartButton() {
    SceneManager.LoadScene(1);
}

【问题讨论】:

  • 你的 StopCoroutine 调用是假的。请参阅 Unity 文档以了解如何正确执行此操作。 docs.unity3d.com/ScriptReference/…
  • 感谢您的回答,但请您解释一下我应该怎么做?我已经看到你提到的链接,但它让我很困惑,因为我是新手,我从 Youtube 教程中获得了这些脚本

标签: unity3d button restart collider


【解决方案1】:

当我重新开始游戏时,只有玩家不会与任何人发生碰撞 障碍

您的碰撞很可能不是问题,但您的StopCoroutine() 电话是问题。因为它目前不会阻止玩家的"Invulnerability",因此一旦碰撞他就不会死。

要解决您需要像这样调整 StopCoroutine() 调用的问题,您可以:

  1. IEnumerator 方法保留为私有成员。
  2. 将已启动的Coroutine 保留为私人成员。

IEnumerator 示例:

// Keep the executing script as a private variable.
// This is needed to stop it with StopCoroutine.
private IEnumerator coroutine;

void Start() {
    coroutine = ExampleIEnumerator();
    // Start the given Coroutine.
    StartCoroutine(coroutine);
    // Stop the given Coroutine.
    StopCoroutine(coroutine);
}

private IEnumerator ExampleIEnumerator() {
    yield return new WaitForSeconds(1f);
}

协程示例:

// Keep the executed coroutine as a private variable.
// This is needed to stop it with StopCoroutine.
private Coroutine coroutine;

void Start() {
    // Start the given Coroutine.
    coroutine = StartCoroutine(ExampleIEnumerator());
    // Stop the given Coroutine.
    StopCoroutine(coroutine);
}

private IEnumerator ExampleIEnumerator() {
    yield return new WaitForSeconds(1f);
}

此外,您还需要在您死后禁用 CapsuleCollider2D 后重新启用它。

GetComponent<CapsuleCollider2D>().enabled = true;

StopCoroutine Unity Documentation

【讨论】:

  • 谢谢你的帮助,但我试过第一个例子,玩家死掉重启后仍然无敌,第二个例子给我2个错误哦,我忘了说,我加了当玩家受伤时它会显示一个无敌图标,当无敌时间用完时它会消失,但是当死亡并重新启动时图标没有显示,我也尝试使用 debug.log 它不会告诉我玩家是否无敌
  • 你能告诉我你在第二个例子中遇到的错误吗?
  • 而且您可能需要在重启后启用 Capsule Collider。 GetComponent&lt;CapsuleCollider2D&gt;().enabled = true;
  • 天哪,在我将GetComponent&lt;CapsuleCollider2D&gt;().enabled = true; 置于 void Start 之后,第二种方法 100% 有效,非常感谢!想了好久哈哈...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2015-12-31
  • 1970-01-01
  • 2018-10-05
相关资源
最近更新 更多