【问题标题】:Unity UI seems to be showing old (cached maybe) valuesUnity UI 似乎显示旧的(可能缓存的)值
【发布时间】:2020-01-05 00:24:09
【问题描述】:

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

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

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

我应该进行“强制 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-interface unity3d


    【解决方案1】:

    线

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

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

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

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

    【讨论】:

    • 是的!固定的。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    相关资源
    最近更新 更多