0
votes

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:

enter image description here

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.

enter image description here


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.

1
Problem is okay but judging the reason of this problem cannot be so easy until you don't paste any clue about creating Box_1, Box_2 kind of objects. - hygull
@hygull what should I provide in extra? The objects were created in the line Instantiate. - knh190
What are box_1 box_2, you are hiding the code - ilansch
@ilansch pls see updated post. - knh190
You created only 1 instance box object, check the .count of liveboxes. Thats why you always target the same instance. Why would you think you have more instances? - ilansch

1 Answers

0
votes

The problem is caused by canvas. But I still don't understand.

The default canvas should work, but I set the canvas render mode to "screenspace - camera" and attached main camera to it (also "worldspace" doesn't work).

I changed back to the default "screenspace - overlay" and now it works.