What I have is a game object that has several child’s in the parent if the child’s I have a script that has an array of GameObject
public var Coins : GameObject;
What I want is to automatically set the child’s of the parent to an array
var ParentObject : GameObject;
var Coins : GameObject[];
function Start () {
//what should I do here to set the childs of the ParentObject on the Coins Array ?
}
You can use GetComponentsInChildren and grab all their transforms because (as far as I know) you cannot remove the transform from a gameObject. This is the idea (element 0 is the parent, but you can get around that):
int value = 0;
public Transform[] childs;
public GameObject[] childObjects;
void Start () {
childs = gameObject.GetComponentsInChildren<Transform>();
childObjects = new GameObject[childs.Length];
foreach(Transform trans in childs) {
value++;
childObjects.SetValue (trans.gameObject, value - 1);
}
}
JS:
value : int = 0;
public var : Transform[] childs;
public var : GameObject[] childObjects;
function Start() {
childs = gameObject.GetComponentsInChildren(Transform);
childObjects = GameObject[childs.Length];
for(var trans : Transform in childs) {
value++;
childObjects.SetValue(trans.gameObject, value - 1);
}
}
This is a robust way to do it, but it will work. I’m not sure about the JavaScript one, but the C# one works for me.
Edit
Easier way would be use Linq and Generic:
using System.Linq;
using System.Collections.Generic;
void Start() {
List<GameObject> list = new List<GameObject>();
foreach(Transform go in obj.transform) {
list.Add (go.gameObject);
}
GameObject[] childrenObjects = list.ToArray();
var go = Selection.activeGameObject;
var allChildren = go.GetComponentsInChildren(Transform);
for (var child : Transform in allChildren) {
print(child.gameObject.name);
if(child.gameObject.GetComponent(MeshRenderer)){
child.gameObject.AddComponent(MeshCollider);
}
}
I taught myself to code at home with reaktor synth, then milkdrop, and most deeply of all, unity3D JS. I think Csharp is a waste of time for someone who just does little games and prototypes, if it can do marching cubes and mesh generation, it’s enough, I hope JS works until version 2025! even if they take it off the front end.