如何检查对象的任何子对象是否处于活动状态?

时间:2021-02-05 06:38:02

标签: c# unity3d

我在我的游戏中创建了武器,并且在使用时我使武器不处于活动状态,但现在玩家可以同时使用 2 支枪。我已将所有武器添加到一个空对象中,我想检查对象的任何子对象是否处于活动状态。所有武器都有相同的脚本,但布尔值不同。 方法就是这样

void OnMouseDown()
    {
            if(weapon_is_taken == false)
            {
                weapon_is_taken = true;
            }
     }

2 个答案:

答案 0 :(得分:1)

根据您的需要,有多种方法。

要回答您的标题,您可以例如使用

public bool IsAnyChildActive()
{
    // Iterates through all direct childs of this object
    foreach(Transform child in transform)
    {
        if(child.gameObject.activeSelf) return true;
    }

    return false;
}

但是,根据孩子的数量,这可能每次都会有点开销。


我假设您的目标是能够关闭活动武器并立即将所有其他武器设置为非活动状态。

为此,您可以简单地将当前活动引用存储在您的武器类中,例如

public class Weapon : MonoBehaviour
{
    // Stores the reference to the currently active weapon
    private static Weapon currentlyActiveWeapon;

    // Read-only access from the outside
    // Only this class can change the value
    public static Weapon CurrentlyActiveWeapon
    {
        get => currentlyActiveWeapon;

        private set
        {
            if(currentlyActiveWeapon == value)
            {
                // Already the same reference -> nothing to do
                return;
            }

            // Is there a current weapon at all?
            if(currentlyActiveWeapon)
            {
                // Set the current weapon inactive
                currentlyActiveWeapon.gameObject.SetActive(false);
            }

            // Store the assigned value as the new active weapon
            currentlyActiveWeapon = value;
            // And set it active
            currentlyActiveWeapon.gameObject.SetActive(true);
        }
    }

    // Check if this is the currently active weapon
    public bool weapon_is_taken => currentlyActiveWeapon == this;

    public void SetThisWeaponActive()
    {
        CurrentlyActiveWeapon = this;
    }
}

答案 1 :(得分:0)

这个上下文中的游戏对象是一个持有子对象(武器)的父对象

  for (int i = 0; i < gameObject.transform.childCount; i++)
        {

            if (transform.GetChild(i).gameObject.activeSelf)
            {
                // do whatever you want if child is active
            }
            else
            {
                // do whatever you want if child is inactive

            }
        }
相关问题