【问题标题】:Referencing bool on another game object not working?在另一个游戏对象上引用 bool 不起作用?
【发布时间】:2022-12-04 00:27:07
【问题描述】:

我有一个带有名为“accept”的脚本的 Hitbox,然后我有 2 个预制件的公共布尔值为“isPoor”。其中一个预制件 = true,另一个 = false。

当带有 isPoor = true 的预制件进入“接受”命中框时,我希望游戏失败,而当 isPoor = false 进入“接受”命中框时,我希望玩家获胜。

我所拥有的代码的问题是它只会使游戏失败,即使 isPoor = false 的 NPC 进入“接受”命中框也是如此。

这是接受点击框的代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class accept : MonoBehaviour
{
    public LayerMask grabbable;
    public GameObject Spawner;
    bool isPoor;
    public GameManager gameManager;

    public void OnTriggerEnter2D(Collider2D other)
    {
        isPoor = other.gameObject.GetComponent<Poor>().isPoor;

        if (isPoor = true)
        {
            gameManager.GameOver();
        }

        if (isPoor = false)
        {
            gameManager.GameWon();
        }

        Destroy(other.gameObject);

        Spawner.GetComponent<Spawner>().Spawn();

    }

}

这是我第一次使用 Unity,所以我有点难过。但似乎脚本只是将两个预制件视为 isPoor = true。

【问题讨论】:

  • isPoor = true分配价值。 isPoor == true是对比。更简单地说,您可以使用if (isPoor) {if (!isPoor) {

标签: c# unity3d 2d


【解决方案1】:

isPoor 设为 class accept 中的一个字段没有意义,因为无论如何您都在 OnTriggerEnter2D 中检索新值。使它成为局部变量。

然后=是赋值,不是比较。使用== 进行比较。但对于布尔值,这不是必需的。像这样测试:

// bool isPoor; drop this declaration!

public void OnTriggerEnter2D(Collider2D other)
{
    bool isPoor = other.gameObject.GetComponent<Poor>().isPoor;
    if (isPoor) {
        // isPoor == true here
        gameManager.GameOver();
    } else {
        // isPoor == false here
        gameManager.GameWon();
    }

    Destroy(other.gameObject);
    Spawner.GetComponent<Spawner>().Spawn();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多