【发布时间】:2021-05-15 06:38:21
【问题描述】:
我想通过单击一个按钮来减少一个值,但是它没有停留在并返回到开头的值, 这是我的代码,我应该添加或更改什么可以帮助我吗?
非常感谢
public class LifeShow : MonoBehaviour
{
public GameObject Life; //where the variable will be decreased from
public int Lifevalue;
public string text;
public Button returns;
// Start is called before the first frame update
void Start()
{
Lifevalue = 1;
Life.GetComponent<Text>().text = "Life : " + Lifevalue;
}
// Update is called once per frame
// clicking the button and the lifevalue variable decreases
void Update()
{
Button btn = returns.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
void TaskOnClick()
{
Lifevalue-- ;
Life.GetComponent<Text>().text = "Life : " + Lifevalue;
}
}
}
【问题讨论】:
-
我试图在代码中的变量附近添加描述,但我不确定它应该如何,因为我是 csharp 和论坛的新手:/
-
你确定要
btn.onClick.AddListener(TaskOnClick)每一帧吗?通常你会注册事件处理程序一次。 -
您应该将 TaskOnClick 函数移到更新函数之外。除此之外,您不需要仅针对此功能进行更新。单独创建 TaskOnClick 函数,更新函数的前 2 行应该在 start 函数内部。那应该可以。
-
我希望每次如果生命值大于 0,在按钮点击时减少,我应该使用其他东西来点击按钮吗?
-
是的,我对 Csharp 很陌生,我正在努力学习。感谢您的帮助
标签: c# unity3d user-interface