- Home /
Instantiated UI ignores parent transform on setactive method
Hi guys,
I'm trying to instantiate a prefab UI canvas, essentially the classic "press E to interact" window, that I want to be able to place on any interactable object. I've managed to instantiate the object, but when I modify the transform, the transform is visibly changed in the hierarchy, but snaps back to the original position after it's enabled. Here's what I mean:
.
.
To be extra obvious, I set the transform to a ridiculous value, all via script, but the UI elements are exactly where they were before I turned them into prefabs. Not really sure what I'm missing here. Here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NPCscript : MonoBehaviour
{
[SerializeField] GameObject gui; //stores a prefab gameobject with a canvas and text fields for dialogue that gets instantiated on awake
GameObject npcChatWindow; //stores the instantiated prefab so I can pass the prefab to the OnTrigger methods and enable/disable them
private void Awake()
{
npcChatWindow = Instantiate(gui);
npcChatWindow.SetActive(false);
Transform test = npcChatWindow.GetComponent<Transform>(); //cache reference
test.position = new Vector3(250, 30000, 0);
}
private void OnTriggerEnter2D(Collider2D collision)
{
npcChatWindow.SetActive(true);
}
private void OnTriggerExit2D(Collider2D collision)
{
npcChatWindow.SetActive(false);
}
}
.
I've realized that editing the transform of the gameobject does exactly that. I can find the gameobject a million miles away from the rest of the scene. The children (being the canvas and the text element) naturally follow this transform, up until the point that the gameobject actually gets enabled (via the OnTrigger method), at which point the canvas transform moves to the same spot the prefab was in when it was created, this is despite the fact that I supplied a transform AFTER the instantiate method is called. Does anyone know why this happens? I really have no idea why this behavior is happening. Thanks for any help.
Your answer
