- Home /
How to acess a Script in 2 spesific Children?
I have dual wield guns in my game and each one has a Script attached to it. However when I was making the ammo pickup script it only changed the first child and not the second. I used GetComponentInChild. I do realize I need to do some kind of foreach but I just can't understand it. This is what i got untill now.
void Update() {
theClip = this.GetComponentInChildren<GunClip>();
theHP = this.GetComponent<PlayersHP>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("healthPickUp"))
{
theHP.health += HpGiven;
}
if (other.CompareTag("ammoPickUp"))
{
theClip.AllBullets += ammoGiven;
}
}
Answer by Reynarz · Jul 21, 2017 at 01:30 AM
I'm in mobile, i will try explain the best i can. if you have a game object you can say in the script attached:
var myComponentInChild = transform.GetChild(/*number of the child*/).GetComponent</*my component*/>();
Just specific the number of the child that the gameObject have, and later get the component that you want. Start the count from zero.
if the two child that have the gameObject have the same script you can say:
var myComponentsFromChilds = GetcomponensInChildren</*my component*/>();
This will return an array with the component of your childrens. and you will could use a for or foreach loop.
the for loop can be something like this:
for(var x = 0; x < myComponentsFromChilds.Lenth; x++)
{
var aComponent = myComponentsFromChilds[x];
aComponent.AllBullets = 15;
}
Answer by Suave · Jul 21, 2017 at 01:48 AM
Could you exemplify the foreach or for loop? I'm not too kneen on it. Thanks for your time i see where you're getting
Either way isnt the GetComponentsInChildren getting multiple components from the same children?
see my edit answer :), and not, that will return the same component in all your chillds. https://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html
I did it right before I saw your post again. Thank you so much I've been knocking my head for 2hours now. I owe you my life kind sir. Have a great evening
Your answer