如何更新脚本c#

本文关键字:脚本 更新 何更新 | 更新日期: 2023-09-27 18:05:19

好的,所以我了解c#的基础知识,并且之前一直在使用unity3d来尝试Visual studio。

目前我有一个简单的按钮和一个文本框与下面的脚本。我有它,所以当按钮被按下时,它会改变文本框中的文本。(我知道这很简单,我已经习惯了Visual studio)。我期望发生的是文本在那个框架上改变,但是它只有在我尝试在文本框中输入一些东西时才会改变。unity中是否有类似于Update()的东西能够更新每帧内的所有内容,或者我该如何获得类似的结果?提前谢谢。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplicationTest
{
public partial class Form1 : Form
{
    public bool ButtonIsPressed = false;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (ButtonIsPressed == true)
        {
            this.textBox1.Text = "ButtonIsPressed is true!";
        } else if (ButtonIsPressed == false)
        {
            this.textBox1.Text = "ButtonIsPressed is false!";
        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        ButtonIsPressed = true;
    }
}

如何更新脚本c#

winforms的工作方式(与unity不同)是使用事件,您为每个控件都有一个事件处理程序,当他被触发时,在其上注册的方法将发生。在您的示例中,您有一个带有事件处理程序的文本框,textBox1_TextChanged已注册到该文本框中,当您对文本框进行任何更改时,将调用方法- textBox1_TextChanged。如果你想在文本框改变时发生多个动作,只需将所有动作(函数)注册到事件处理程序。

正如Andrey所说,只有当字段中的Text被更改时,TextChanged才会触发。要得到想要的结果,必须使用其他事件:

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        textBox1.Text = "pressed";
    }
    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        textBox1.Text = "not pressed";
    }

单击按钮时发生的唯一事情是您的ButtonIsPressed变量的值发生了变化。在文本框中输入一些东西会触发TextChanged事件,该事件由textBox1_TextChanged方法处理。然后在处理程序中修改文本框的内容。