Assign a prefab as childs to several gameobjects
Hi everyone,
In my scene I have numerous cubes, I added a tag to all these cubes, than I would like to assign this prefab as child to each cubes. How can I manage this ?
To find gameobject with tag I use:
"GameObject.FindGameObjectsWithTag ;" and then "foreach (GameObject X in Y) "
I'm kind of beginner in scripting.
Thank you for your time and your help. Regards,
Answer by brunocoimbra · Nov 21, 2016 at 04:16 PM
You can do something like that:
public void InstantiateInAllObjectsWithTag(GameObject original, string tag)
{
var allTargets = GameObject.FindGameObjectsWithTag(tag);
foreach (var target in allTargets )
{
GameObject instance = Instantiate(original) as GameObject;
instance.transform.SetParent(target);
}
}
Thank you, it almost works, I don't know what I did wrong in my script, I have an error message "(UnityEngine.Transform.SetParent(UnityEngine.Transform) has some invalid arguments". I assume it's a problem with "target" ... But because I'm a beginner I'm not sure o know how to manage that.
Thanks for your help !
here's my script :
using UnityEngine; using System.Collections;
public class AssignChild : $$anonymous$$onoBehaviour {
GameObject[] Light;
public void InstantiateInAllObjectsWithTag (GameObject Original, string Spheres)
{
var Light = GameObject.FindGameObjectsWithTag(Spheres);
foreach (var target in Light)
{
GameObject instance = Instantiate(Original) as GameObject;
instance.transform.SetParent(target);
}
}
}
Oh, sorry about that!
It should be instance.transform.SetParent(target.transform);
Thank you for your help :), I still have an issue :/ I certainly miss something, I tagged my light reference as "Original" and all my spheres are tagged with the tag "Spheres". Did I forgot something ?
Thanks alot for your help
Here's my script :
using UnityEngine; using System.Collections;
public class AssignChild : $$anonymous$$onoBehaviour {
public void InstantiateInAllObjectsWithTag (GameObject Original, string Spheres)
{
var Light = GameObject.FindGameObjectsWithTag(Spheres);
foreach (var target in Light)
{
GameObject instance = Instantiate(Original) as GameObject;
instance.transform.SetParent(target.transform);
}
}
}