- Home /
Position of parent from grandchild
I am trying to find a position of gameObject. Script is attached to a text which is in canvas (to render properly) of gameObject. I am trying to render the position of gameObject (Hexagon). I tried using transform.local.Position but it gives the position of text on screen.
Text is attached like this.
This is the script I have.
public class DisplayInfo : MonoBehaviour
{
Text text;
void Awake()
{
text = GetComponent<Text>();
}
void Update()
{
Vector2 pos = transform.parent.parent; //this gives me error cannot implicitly convert type 'unityengine.transform' to 'unityengine.vector2
text.text = pos.ToString();
}
}
Answer by MickyX · May 03 at 04:45 PM
Its a little hard to help with the information you have provided but a couple few things
.
Can you use TextMeshPro instead of Text? (Text is depreciated) and TextMeshPro can be used without a canvas which would remove your grandparent
Assuming the hexagon is a 3d object which it looks like, You can't access the Vector 2 position as it doesn't have one it is a vector 3 and the Hexagon is in 3d space. If you only want to show two positions x and y you can get them from the vector3
If you really want to use what you have above try this and see if it gives you what you want.
void Update()
{
Vector3 pos = transform.parent.parent;
text.text = pos.x + " " + pos.y;
}
Thank you for your response. I tried your method but it still gives me error. I managed to make it work throught GamjeObject.Find. Here is the code i you are interested:
var gobj = GameObject.Find(hexagon.name);
if(gobj)
{
Vector2 vector = gobj.transform.position;
text.text = vector.ToString();
}