- Home /
ChildCount without counting the children of the child ?
i'm making a drop pick up program and i need to make a limit like u cant pick up if u have a child in the weapon holder and u can when there's no children the issue is my weapon object has children as game objects for the shooting script muzzflashes and trail effect stuff like that i need to calculate the child of the weapon holder without counting the weapon's children is it possible thanks
Answer by FlaSh-G · Sep 13, 2021 at 12:36 PM
I don't really understand the context, but you can iterate over a Transform to have all its children:
foreach (Transform child in transform)
So you can just count yourself:
var childCount = 0;
foreach (Transform child in transform)
{
childCount++;
}
With this, you can implement whatever you want.
That being said, I also just checked Transform.childCount
in 2020.3.17, and it only counts direct children of an object anyway, children of children are ignored.
what if i use it with a tag ? can this work ?
for (int i = 0; i < t.childCount; i++)
{
if(t.GetChild(i).gameObject.tag == tag)
{
return t.GetChild(i).gameObject;
}
Sure, why not! It would work with a foreach loop as well.
foreach (Transform child in transform)
{
if (child.gameObject.CompareTag(tag))
{
return child.gameObject;
}
}
it works but i really need the childcount to be 0 or 1 cuz if its not the player can pickup 2 weapons which is not ideal is that posible to force it to be 0 or 1 ? if (transform.parent == holder && holder.childCount ==1 ) { Pickedup = true;
}
if (transform.parent != holder && holder.childCount == 0)
{
Pickedup = false;
}
else if (holder.childCount > 1)
{
}
print(holder.childCount);
No, you cannot force a count. Your code is going in the right direction here; check whether a child already exists (`childCount > 0`) and if it does, decide what to do next. Either you refuse to pick up another item or destroy the current one.
Answer by logicandchaos · Sep 13, 2021 at 01:09 PM
If you there is a script on the components you want to get, you can use GetComponentsInChildren()
Your answer
![](https://koobas.hobune.stream/wayback/20220613042953im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Best way to create a flamethrower weapon in 2d? 1 Answer
How do I stop my weapon from firing while reloading? 2 Answers
Can't set an int from seperate script 1 Answer
Reload with keypress work bad! 0 Answers
Weapon shooting mechanism problem. 1 Answer