簡體   English   中英

如何逐步使用功能

[英]How to use functions step by step

抱歉,標題很奇怪,我只是不知道如何命名這個問題。

所以我有這樣一個功能say()

void say(string printedText) {
    gameText.text = printedText;
}

我需要多次使用它。 像這樣:

say("test text 1");
say("test text 2");
say("test text 3");
...

我需要通過單擊空格按鈕來更改文本。 當然我需要使用這樣的東西:

if(Input.GetKeyDown(KeyCode.Space)) {
   ...
}

但是我不明白如何逐步顯示文本。 因此,例如,如果單擊一次“空格”按鈕,我應該看到“測試文本1”。 下一步應顯示“測試文本2”等。

我怎么知道呢? 提前致謝。

根據您的需要,您可以將不同的文本存儲在List<string>甚至Queue<string>然后執行

清單范例

// Add your texts in the editor or by calling texts.Add(someNewString)
public List<string> texts = new List<string>();

private int index = 0;

if(Input.GetKeyDown(KeyCode.Space)) 
{
    // have a safety check if the counter is still within 
    // valid index values
    if(texts.Count > index) say(texts[index]);
    // increase index by 1
    index++;
}

數組示例

基本上與List<string>相同,但是您不能“即時”添加或刪除元素(至少不是那么簡單)

public string[] texts;

private int index = 0;

if(Input.GetKeyDown(KeyCode.Space)) 
{
    // have a safety check if the counter is still within 
    // valid index values
    if(texts.Length > index) say(texts[index]);
    // increase index by 1
    index++;
}

隊列示例

public Queue<string> texts = new Queue<string>();

用於向隊列末尾添加新文本

texts.Enqueue(someNewString);

接着

if(Input.GetKeyDown(KeyCode.Space)) 
{
    // retrieves the first entry in the queue and at the same time
    // removes it from the queue
    if(texts.Count > 0) say(texts.Dequeue());
}

簡單櫃台

如果實際上只是要具有一個不同的int值,那么只需使用一個字段

private int index;

if(Input.GetKeyDown(KeyCode.Space)) 
{
    // uses string interpolation to replace {0} by the value of index
    say($"test text {0}", index);
    // increase index by one
    index++;
}

定義一個這樣的類字段:

int count = 0;

現在每次遇到空間時:

if(Input.GetKeyDown(KeyCode.Space)) {
    say("test text " + count);
    count = count + 1;
}

此代碼:

if(Input.GetKeyDown(KeyCode.Space)) {
   ...
}

僅適用於Unity,在Visual Studio中,您必須為要執行此操作的任何對象創建一個Event,例如,如果要在每次按空格鍵時調用void,則必須這樣做,這很容易: (下圖)

在屬性窗口中,按螺栓圖標,然后雙擊要創建的事件(樣本):TextChanged,LocationChnaged,MouseMove等。

我將在TextBox對象上使用KeyDown

圖片

現在,在您的代碼中,應該生成此void

圖片

在這個空白中,我編寫了代碼,看起來是這樣的:

(將int n = 1置於空位之前)

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Space)
            {
                //int n = 1; must be defined
                textBox1.Text = "test text " + n; 
                n++;
            }
        }

現在,每次您按下或保持按下空格鍵時,文本框將填充“測試文本”,並且每次的值將增加1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM