- Home /
How do I access childs with name and getComponent them ?
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 ?
Answer by danmartelly_caliper · May 26, 2017 at 12:30 PM
You can use Transform.Find
as long as the names are unique as they are in your case (https://docs.unity3d.com/ScriptReference/Transform.Find.html). 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>();
Another good way of doing it! Personally, I'd add some if statements in case the Transforms aren't found, otherwise the user will get NullReference Errors :)
Answer by Cherno · May 26, 2017 at 10:21 AM
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;
}
}
Answer by Emiles · May 26, 2017 at 05:06 PM
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>
}
}
Answer by MichaelJT · May 26, 2017 at 05:43 PM
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.