- Home /
Transform [] = all children of this game object ? (Spawnpoints)
their has to be an easier way then to drag and drop 30+ Game Objects :)
I have "Spawn points" for where enemies can spawn, Can I have all my GameObjects under a ""Master"" Game Object and go Transform[] = and get al the Children transforms? Drag and dropping for every spawn point is ridiculous their has to be a simpler way of doing this :)
[SerializeField]
private Transform[] spawnPoints; // drag and drop in Inspector
private Transform spawnPointTransform;
public FighterCounter FighterCount;
public GameObject MissionControll;
public bool destroyer;
public bool BattleShip;
public bool Carrier;
public bool Fighter;
public bool OurTeam;
void Start(){
FighterCount = MissionControll.gameObject.GetComponent<FighterCounter> ();
}
// Use this for initialization
void LateUpdate () {
if (PhotonNetwork.isMasterClient) {
if(FighterCount.TeamOneFighters > 0 && Fighter == true && OurTeam == true){
int index = Random.Range(0, spawnPoints.Length);
spawnPointTransform = spawnPoints[index];
PhotonNetwork.Instantiate ("T1FighterA", spawnPointTransform.position, spawnPointTransform.rotation, 0);
FighterCount.TeamOneFighters -= 1;
}
}
You already got your answer, but you can also select all of them at once and then drag & drop in inspector. Clicking the small lock icon at the top right corner of inspector will lock the currently selected object so it doesn't change while you are selecting items that you want to drag.
Answer by HarshadK · Mar 07, 2017 at 09:38 AM
This should do it:
public Transform SpawnPointContainer; // Assign parent gameobject of spawn points.
private Transform[] spawnPoints;
void Start()
{
// Initialize spawnPoints array.
spawnPoints = new Transform[spawnPointContainer.childCount];
// Populate array with child transforms.
for(int i = 0; i < spawnPointContainer.childCount; i++) {
spawnPoints[i] = spawnPointContainer.GetChild(i);
}
}
Answer by ExtinctSpecie · Mar 07, 2017 at 09:38 AM
yes you can have an array of all child objects could be something like this
public static Transform[] spawnPoints;
spawnPoints = new Transform[transform.childCount];
for (int i = 0; i < spawnPoints.Length; i++)
{
spawnPoints[i] = transform.GetChild(i);
}
//this script has to be attached to the parent object otherwise you will have to pass the Transform component of that parent object
Answer by Bunny83 · Mar 07, 2017 at 11:54 AM
Here's a one-liner:
// at the top
using System.Linq;
void Start()
{
spawnPoints = spawnPointTransform.Cast<Transform>().ToArray();
}
However essentially it does the same as the code that HarshadK or ExtinctSpecie posted, just in one line using Linq. Note that even though this looks "shorter" it's not "faster" or "better". It's actually a bit worse from a performance point of view. I just posted the solution for those who prefer "short code" ^^.