简体   繁体   English

如何访问预制的按钮文本子项?

[英]How to access prefab's button text child?

I'm trying something and I have a button in my prefab.我正在尝试一些东西,我的预制件中有一个按钮。 I want to bind the texts in the text of the button to the variable.我想将按钮文本中的文本绑定到变量。 For example, on my button, the price of the product is written.例如,在我的按钮上,写有产品的价格。 I'm changing the price somewhere in the game, but I cannot change the text of the price in the button.我正在游戏中某处更改价格,但我无法更改按钮中的价格文本。 How can I get the text of the button in the prefab?如何获取预制中按钮的文本?

There are thousands of ways you can achieve this.有成千上万种方法可以实现这一目标。 I'll be explaining 1 solution which you can use (easiest, assuming button is static).我将解释您可以使用的 1 个解决方案(最简单,假设按钮是静态的)。

Solution:解决方案:

Button is static in scene, ie you are not instantiating the button dynamically.按钮在场景中是 static,即您没有动态实例化按钮。

In the script which deals with changing the price (where price is stored in variable), make another variable:在处理更改价格(价格存储在变量中)的脚本中,创建另一个变量:

public Button thisButton;

In the Inspector, you'll see this variable exposed now.在 Inspector 中,您会看到这个变量现在暴露了。 You can drag and drop button from your scene to this thisButton variable in Inspector.您可以将按钮从场景拖放到 Inspector 中的 thisButton 变量。

Now wherever you need to update the text, you can update the text in this way现在无论哪里需要更新文字,都可以用这种方式更新文字

public void UpdateButtonText(string text)
{
  thisButton.GetComponentInChildren<Text>().text = text;
}

Now you can call the function "UpdateButtonText(string)" with updated price that you need to update on the button.现在您可以调用 function "UpdateButtonText(string)" 并更新您需要在按钮上更新的价格。

Let me know if you're dynamically instantiating the button at runtime, I'll explain another solution then.如果您在运行时动态实例化按钮,请告诉我,然后我将解释另一种解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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