- Home /
How to write a script for a gameObject that refers to all children?
HI!! I'm working on a project (a church) in Unity because I want to put it into the Dive. I'm trying to write a script for the parent (that is all my church exported from 3dSMax) that refers to every child (walls, windows, roofs...). I would like that clicking an object or better a child (a wall, a window..) a box appears with some information inside: how can I do this? Every child is a mesh collider in Unity and I have to work with Raycast and 3Dtext, because this project will be visible in the DIVE. I would be very happy if you could help me out with some information about this problem. Thanks a lot.
Comment
Answer by jmgek · Nov 04, 2016 at 11:55 PM
gameObject.GetComponentsInChildren<Transform>(); //To get the scripts
//Or
List<gameObject> newList = new List<gameObject();
foreach (Transform child in Church)
newList.Add(child);
Answer by frederik99 · Nov 05, 2016 at 12:13 PM
I hope i got it right
using UnityEngine;
public class ChurchChildrenInfoDisplay : MonoBehaviour {
public ChildInformation[] childInformationArray;
private void Start() {
//usage example
childInformationArray = new ChildInformation[] {
new ChildInformation(GameObject.Find("Wall").transform, "This is a wall."),
new ChildInformation(GameObject.Find("Window").transform, "This is a window.")
};
}
private void Update () {
if (Input.GetMouseButtonDown(0)) {
Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(mouseRay, out hit)) {
Transform hitTransform = hit.transform;
ChildInformation hitChildInfo = GetChildInformationOfTransform(hitTransform);
if (hitChildInfo != null) {
OnChildClicked(hitChildInfo);
}
}
}
}
private ChildInformation GetChildInformationOfTransform(Transform child) {
foreach (ChildInformation childInfo in childInformationArray) {
if (childInfo.transform == child) {
return childInfo;
}
}
return null;
}
private void OnChildClicked(ChildInformation childInfo) {
//display a box with some information inside
}
}
[System.Serializable]
public class ChildInformation {
public ChildInformation() {
}
public ChildInformation(Transform transform, string info) : this() {
this.transform = transform;
this.info = info;
}
public Transform transform;
//this can be any (or several) datatype(s)
public string info;
}
Your answer
