首页 > 解决方案 > Unity UI 似乎显示旧的(可能缓存的)值

问题描述

我有一个 UIPanel Prefab (ItemDetailedView GameObject),它有自己的脚本 (ItemDetailedView.cs)

我实例化 ItemDetailedView GameObject,然后获取它的组件脚本并告诉它显示项目的详细信息。

问题是,详细信息视图总是显示我查看的最后一项。即使游戏停止并重新启动,第一个项目视图也将是我上次运行游戏时查看的最后一个项目!

我应该进行“强制 GUI 更新”调用吗?

//This is set to the prefab in the inspector
public GameObject ViewItemPrefab

//called from an inventory view button listener
private void ViewDetails(Item item)
{
     //Shows the correct item.Name
     print("about to show details for " + item.Name);

     //instantiates nicely
     Instantiate(ViewItemPrefab, transform.parent);
     ViewItemPrefab.GetComponent<GUIDetailedItemViewWindow>().Show(item);
}

public class GUIDetailedItemViewWindow : MonoBehaviour
{
    private Item item;

    //text UI object set in the inspector
    public Text ItemNameText;

    public void Show(Item itemToShow)
    {
        //this prints the right Name
        print("itemToShow name: " + itemToShow.Name);

        item = itemToShow;

        //this prints the right Name too!
        print("Item to view details for: " + item.Name);

        //this shows the Name of the last Item we were looking at!
        // this is the problem here!
        // it will even show the name of the item I looked at last time I ran the game!
        ItemNameText.text = item.Name;


        //now it gets really weird
        //this shows the correct item name!
        print("ItemNameText.text is " + ItemNameText.text);

    }
}

下次我尝试查看某个项目的详细信息时,它将显示我们尝试查看其详细信息的最后一个项目。

我完全感到困惑。

谢谢!

标签: c#user-interfaceunity3d

解决方案


线

ViewItemPrefab.GetComponent<GUIDetailedItemViewWindow>().Show(item);

获取prefab的组件,而不是新实例化的对象。

这就是为什么您在下次创建窗口时会看到这些值的原因,以及它在游戏重置后仍然存在的原因(仅恢复了场景,但您修改了预制件)。要访问新对象,请执行以下操作

GameObject details = Instantiate(ViewItemPrefab, transform.parent);
details.GetComponent<GUIDetailedItemViewWindow>().Show(item);

推荐阅读