How do I access childs with name and getComponent them ?

94669-untitled.png

I have this Heirarchy where “StrongAquaragia” and “Strong Aquaragia” are gameobjects and model is a 3d model and Strong Aquaragia break/fx are particle systems.

Now I have attached a C# script to the topmost parent “StrongAquaragia”. I have to access the particle systems “Strong Aquaragia break” and “------fx” seperately as different particle systems and need to assign it to variables like m_Explosion and m_fx.

I have tried a lot but not getting it. How do I do it ?

The best way would be to have variables in your c# script holding references to the two ParticleSystems so you can access them directly anytime. GetComponent is expensive and should be avoided if possible, especially if it is used every frame.

To answer your question:

foreach(ParticleSystem ps in GetComponentsInChildren<ParticleSystem>()) {
     if(ps.gameObject != gameObject && ps.gameObject.name == "Strong Aquaragia break") {
     //do whatever you want with the ...break ParticleSystem
     Debug.Log("Found " + ps.name);
     m_Explosion = ps;
     }
     if(ps.gameObject != gameObject && ps.gameObject.name == "Strong Aquaragia fx") {
          //do whatever you want with the ...fxParticleSystem
          Debug.Log("Found " + ps.name);
          m_fx = ps;
     }
}

You can use Transform.Find as long as the names are unique as they are in your case (Unity - Scripting API: Transform.Find). Transform.Find will find the first child object with that name and return it. So you could do something like this:

m_Explosion = this.transform.Find("Strong Aquaragia break").GetComponent<ParticleSystem>();
m_fx = = this.transform.Find("Strong Aquaragia fx").GetComponent<ParticleSystem>();

public class StrongAquaragia : Behaviour
{
// Drag the components in your heirachy onto the inspector properties…
public ParticleSystem particle1;
public ParticleSystem particle2;
void Awake(){
particle1.m_Explosion = 10000; /// Which ever particle properties you want to change>
}
}

Start by declaring the two particle systems. You could probably try renaming them to something simpler too.

public ParticleSystem break;
public ParticleSystem fx;

Start()
{
     break = gameObject.transform.Find("particle_break").GetComponent<ParticleSystem>();
     fx = gameObject.transform.Find("partical_fx").GetComponent<ParticleSystem>();
}

This should work. Of course you can also assign them in the inspector if you want.

They only really need to be public variables if you want to assign them in in the inspector or control them from another script that isn’t attached to the root GameObject.