如何让 Player 忽略与代码中另一个 GameObject 的碰撞?

How can I bring a Player to ignore collision with another GameObject in code?

我目前正在尝试为我的游戏编写健康系统代码,我希望我的玩家游戏对象在玩家拥有最大生命值时忽略与健康药水游戏对象的碰撞。我的问题是我不能简单地关闭 Player Layer 和 Health Potion Layer 之间的碰撞,因为我只想在 Player 具有 Max Health 时忽略碰撞。我尝试自己做,但没有用。这是我的代码:

public class ExampleCodeUA : MonoBehaviour{

public int PlayerMaxHealth = 100, PlayerCurrentHealth;
public HealthBar healthBar;

private void Start()
{
    PlayerCurrentHealth = PlayerMaxHealth;
}

    private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("HealthPotion"))
    {
        if (PlayerCurrentHealth == PlayerMaxHealth)
        {
            Physics2D.IgnoreLayerCollision(6, 7);
        }
        else if (PlayerCurrentHealth > 50)
        {
            GetHealth(PlayerMaxHealth - PlayerCurrentHealth);
        }
        else if (PlayerCurrentHealth <= 50)
        {
            GetHealth(50);
        }

    }
}

void GetHealth(int healing)
{
    PlayerCurrentHealth += healing;
    healthBar.SetHealth(PlayerCurrentHealth);
}

}

您不想在运行时修改您的物理配置。你可以做些什么来避免碰撞……就是让碰撞变得不可能,因为没有任何碰撞。你的两个物体都有一个对撞机。您可以做的是通过修改代码来禁用所有现有的 HealthPotion 碰撞器。一个实现可能如下:

using System.Collections.Generics;
using UnityEngine;

public class HealthPotion : MonoBehaviour
{
    private static List<HealthPotion> _existingPotions = new List<HealthPotion>();

    public static void EnablePotionsCollider(bool value)
    {
        foreach (var potion in _existingPotions)
        {
            potion._collider.enabled = value;
        }
    }

    private Collider _collider;

    void Awake()
    {
        _collider = GetComponent<Collider>();
    }

    void OnEnable()
    {
        _existingPotions.Add(this);
    }

    void OnDisable()
    {
        _existingPotions.Remove(this);
    }
}

然后你只需要在你想enable/disable的时候调用这个方法

HealthPotion.EnablePotionsCollider(value you want);