c# - 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);
}
}
下次我尝试查看某个项目的详细信息时,它将显示我们尝试查看其详细信息的最后一个项目。
我完全感到困惑。
谢谢!
解决方案
线
ViewItemPrefab.GetComponent<GUIDetailedItemViewWindow>().Show(item);
获取prefab的组件,而不是新实例化的对象。
这就是为什么您在下次创建窗口时会看到这些值的原因,以及它在游戏重置后仍然存在的原因(仅恢复了场景,但您修改了预制件)。要访问新对象,请执行以下操作
GameObject details = Instantiate(ViewItemPrefab, transform.parent);
details.GetComponent<GUIDetailedItemViewWindow>().Show(item);
推荐阅读
- javascript - 如何在 Taglist 环境中创建变量 Shiny
- java - Firebase / GeoQuery - 最大半径 IF 语句
- android - 如何禁止在 expo / react-native 中使用平板电脑?
- c# - 在上下文中调用 Find、Add、Update 等时绕过 DBSet 是否有缺点?
- node.js - 使用 NodeGit 在存储库中执行 `git clean`
- rest - Http.post 在flutter/dart 中不接受内容类型application/query+json
- php - Laravel 7 Auth 没有 HomeController
- c - 递归计算标准差
- mysql - 查询错误结果 JPA Spring Boot
- c++ - 如何重新着色二进制图像中的形状以进行索引(填充)?