I have code below to instantiate a UI element and move it:
void PopDialogBox()
{
Vector3 pos = new Vector3(-horzExtent + .5f, -vertExtent, 0f);
GameObject box = Instantiate(dialogBoxPrefab, pos, Quaternion.identity, canvas.transform);
box.name = "Box_" + Time.time;
liveBoxes.Add(box);
for (int i = 0; i < liveBoxes.Count; ++i)
{
Debug.Log("Move " + liveBoxes[i].name);
StartCoroutine(SmoothMoveDialogBox(liveBoxes[i]));
}
}
But the box is always the first created GameObject - they are referencing to the same object. As I can see in log and inspect using breakpoint:
But actually I have 2 or more instantiated objects! Since Box_1.005764 and Box_2.025746 both exist, while in log I can only see Box_1.005764 being referenced.
The boxes were created per second and named accordingly to the time.
I'm confused because I'm using the object after instantiation so it should not be the prefab/previous ones, why this still happens?
As comments questioned, I replaced the for loop as below:
for (int i = 0; i < liveBoxes.Count; ++i)
{
Debug.Log("Move " + liveBoxes[i].name + ", all: " + liveBoxes.Count);
StartCoroutine(SmoothMoveDialogBox(liveBoxes[i]));
}
It clears show that I have more than one boxes but they were not moving. But, I found if I resize the game window they occasionally move, and stop moving at certain point.
For @derHugo, the movement coroutine moves the target box:
IEnumerator SmoothMoveDialogBox(GameObject box)
{
Vector3 pos = box.transform.position;
Vector3 end = pos;
end.y += boxMoveDistance;
Debug.Log(box.name + " from " + pos + ", to " + end);
while (Vector3.Distance(pos, end) > Mathf.Epsilon)
{
Vector3 target = Vector3.MoveTowards(pos, end, boxMoveSpeed);
box.transform.position = target;
pos = box.transform.position;
yield return null;
}
}
For any furthur check see this gist.


Instantiate. - knh190