简体   繁体   中英

Unity instantiated object always references to same object

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM