Search code examples
unity-game-engineinstances

Unity - Text object instancing at wrong position


I'm instancing a small UI canvas with text to appear above a pick up on contact:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PickUpCheck : MonoBehaviour {
public GameObject pickUp;
public GameObject textBox;
public GameObject particle;
private Vector3 pickUpPos;

// Use this for initialization
void Start () {
    pickUpPos = pickUp.transform.position;
}

void OnTriggerEnter2D(Collider2D collider)
{
    Instantiate(particle, pickUpPos, new Quaternion());
    Instantiate(textBox, pickUpPos , new Quaternion());
    Destroy(pickUp.gameObject);
    }
} 

The canvas and text appear somewhere else though. Specifically, at the position of the text object I originally reference in the editor.

enter image description here

I'm not sure why this is overriding the position set in the instance code. I've moved the referenced canvas object prefab around (including to the origin) and re-referenced it to the pick up object and it always will appear at this position instead of the pick up position.

Edit - Just to clarify, pickUp is the game object this script is attached to. The GameObject particle is a particle effect set to instance when the object is collided with. It is unrelated to the current problem.


Solution

  • So I found a simple solution to the problem - I assigned the instance of the created object to a variable and then set the position of that variable to the position of the pick up object:

    void OnTriggerEnter2D(Collider2D collider)
    {
        pickUpPos = pickUp.transform.position;
        textBox = Instantiate(textBox, pickUpPos , new Quaternion());
        textBox.transform.position = pickUpPos;
        Destroy(pickUp.gameObject);
    }
    

    Works as intended now.