- Home /
Finding an objects children when they don't have any scripts attached?
Hey guys I've been searching for over an hour for a solution but I came up empty handed so I apologize if I overlooked a solution for this posted by someone else already.
I have a script attached to my PlayerController that is going to be in charge of selecting a random respawn point for the player. The spawn points are empty game objects placed around the scene.
I am attempting to do this in a way where I don't have to attach the script to the spawn points themselves.
So player script finds the Parent object of the spawn points, then from there grabs the children and adds them into a list, then whenever the respawn is triggered it is supposed to select a random respawn location from the list and move the player to its location.
Yes it would just be easier to attach the script to the parent of the spawn points and grab the children that way but I don't want to do that simply because I already know how to do that but I don't know how to find an objects children that doesn't have any scripts on it and I'm forcing myself to learn new ways of doing things.
Here's my code using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour
{
private Transform spawnPointParent;
private Transform spawnPointChild;
private List<Transform> spawnLocList = new List<Transform>();
void Start()
{
spawnPointParent = transform.Find("Player Respawn Locations"); //Find Parent
spawnPointChild = GetComponentInChildren<Transform>(); //FIX MEEEEEEEEEE
//Do something for each spawn location
foreach (Transform spawnLocs in spawnPointChild)
{
spawnLocList.Add(spawnPointChild); //Add em to the list!
}
Debug.Log(spawnLocList);
Debug.Log(spawnPointChild);
Debug.Log(spawnPointParent);
Respawn(spawnLocList); //Pass the spawnLocList over to the Respawn method
}
public void Respawn(List<Transform> spawnList)
{
Transform randomSpawn = spawnList[Random.Range(0, spawnList.Count)];
Vector3 spawnLoc = new Vector3 (randomSpawn.transform.position.z, randomSpawn.transform.position.y, randomSpawn.transform.position.z);
transform.Translate(spawnLoc); //Move yaself
}
}
Answer by Beks_Omega · Sep 26, 2017 at 04:42 PM
https://docs.unity3d.com/ScriptReference/Transform.GetChild.html and https://docs.unity3d.com/ScriptReference/Transform-childCount.html
or http://answers.unity3d.com/questions/10417/how-can-i-access-the-children-of-a-transform.html
Hopefully one of those can help you out! :D good luck!
Thanks, I will go over those and see what I can find. I tried GetChild but I can't seem to get it to work correctly for what I need.
Your answer
Follow this Question
Related Questions
How can I find gameObject child. 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Dissolve shader script little proplemo, help me 0 Answers
Global Fog Messy Transition Between Objects and Skybox 1 Answer