Getting Parent GameObject from Child?
I'm trying to reference a cloned prefab, so that when a child of it is clicked, it goes back to the prefab and makes changes to it. Since the prefab is cloned, it needs to directly reference from child to the parent. Although I can only use transform.parent, which only gets the transform of the prefab, which is not what I need. My current script that only gets transforms looks like this.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class HappyChanger : MonoBehaviour { public Transform parentPrefab; public Transform parentOfParent; public Transform studentPrefab;
// Use this for initialization
void Start () {
parentPrefab = this.transform.parent;
parentOfParent = parentPrefab.transform.parent;
studentPrefab = parentOfParent.transform.parent;
}
// Update is called once per frame
void Update () {
}
void OnMouseDown()
{
studentPrefab.GetComponent<TalkScript>().sadness = studentPrefab.GetComponent<TalkScript>().sadness - 1;
studentPrefab.GetComponent<TalkScript>().happiness = studentPrefab.GetComponent<TalkScript>().happiness + 1;
}
}
It would really help if I could get an answer to this, thank you!
Answer by Larry-Dietz · Dec 31, 2017 at 05:14 AM
Once you have the parent transform, you are able to access the parent gameobject with transform.gameObject
If you are trying to get to something other than the GameObject of the parent, let us know exactly what you are trying to get to.
Hope this helps, -Larry