Question by
Fallen150 · Dec 27, 2016 at 02:26 PM ·
c#positionprefab-instance
How do I find out the current object I instantiated in the scene?
I'm making an attack functionality which teleports you to an object that I shot out from my player.
if (facingRight)
{
GameObject tmp = (GameObject)Instantiate(Orb, rangedPos.position, Quaternion.identity);
tmp.GetComponent<Orb>().Initialize(Vector2.right);
}
else
{
GameObject tmp = (GameObject)Instantiate(Orb, rangedPos.position, Quaternion.identity);
tmp.GetComponent<Orb>().Initialize(Vector2.left);
}
This is the instantiating method which works perfectly fine. I tried to do this in the Update:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
player.position = Orb.transform.position
}
}
But it just teleports me to 0.0, 0.0, 0.0 in my scene cause that's where my original orbprefab is which is not what I want. How do I reference the Orb that I Instantiated in my Instantiating function and get its current position as its moving?
Comment
Answer by phxvyper · Dec 27, 2016 at 06:31 PM
Your variable Orb
is not changing at all. Instantiate merely copies the content from that variable and creates a new game object, which you assign to tmp
. You should have a variable in your class that you assign tmp
to, and call that in Update
... like so:
GameObject tmp;
...
if (facingRight)
{
tmp = (GameObject)Instantiate(Orb, rangedPos.position, Quaternion.identity);
tmp.GetComponent<Orb>().Initialize(Vector2.right);
}
else
{
tmp = (GameObject)Instantiate(Orb, rangedPos.position, Quaternion.identity);
tmp.GetComponent<Orb>().Initialize(Vector2.left);
}
...
void Update() {
if (tmp != null) player.position = Orb.transform.position;
}