I have created weapons in my game and I made weapons not be active when it is taken but now Player can take 2 guns at the same time. I have added all my weapons to an empty object and I want to check if any child of object is active. All of the weapons have same script but but values of booleans are different. method is like that
void OnMouseDown()
{
if(weapon_is_taken == false)
{
weapon_is_taken = true;
}
}
There are multiple ways depending a bit on your needs.
To answer your title you could e.g. use
public bool IsAnyChildActive()
{
// Iterates through all direct childs of this object
foreach(Transform child in transform)
{
if(child.gameObject.activeSelf) return true;
}
return false;
}
However, depending on the amount of childs this is maybe a bit overhead every time.
I assume your goal is to be able to switch out the active weapon and immediately set all other weapons to inactive.
For this you could simply store the current active reference in your Weapon class like e.g.
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;
}
}
Gameobject in this context is a parent object that holds child objects (weapons)
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
}
}