Unity - Text object instancing at wrong position

时间:2018-03-25 19:35:51

标签: unity3d instances

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.

2 个答案:

答案 0 :(得分:1)

You're setting the position on Start() which means that it'll get set once when you start running the game.

Have you tried setting it when you need the current position, like this?

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

答案 1 :(得分:0)

所以我找到了一个简单的问题解决方案 - 我将创建的对象的实例分配给变量,然后将该变量的位置设置为拾取对象的位置:

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

现在按预期工作。