Unity Number向导后退按钮

时间:2018-08-31 12:14:26

标签: c# unity3d 2d

我刚刚创建了一个数字游戏,女巫猜出了您在想什么数字,并将其作为TextMeshProUGUI元素显示在屏幕上。我想添加一个后退按钮,以便当您按下不正确的按钮时,TextMeshProUGUI元素显示在用户按下不正确的按钮之前显示的值。

脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class NumberWizard : MonoBehaviour {

[SerializeField] SceneLoader sceneLoader;
[SerializeField] int max;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;

int guess;

// Use this for initialization
void Start ()
{
    StartGame();
}

void StartGame()
{
    NextGuess();
}

public void OnPressHigher()
{
    min = guess + 1;
    NextGuess();
}

public void OnPressLower()
{
    max = guess - 1;
    NextGuess();
}

void NextGuess()
{
    guess = Random.Range(min, max+1);
    guessText.text = guess.ToString();
}

public void Back()
{
    //Back code should go here
}
}

Scene View

1 个答案:

答案 0 :(得分:1)

您只需要记住最后一个猜测:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class NumberWizard : MonoBehaviour {

[SerializeField] SceneLoader sceneLoader;
[SerializeField] int max;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;

int guess;
int lastGuess;
int lastMin;
int lastMax;

// Use this for initialization
void Start ()
{
    StartGame();
}

void StartGame()
{
    NextGuess();
}

public void OnPressHigher()
{
    lastMin = min;

    min = guess + 1;
    NextGuess();
}

public void OnPressLower()
{
    lastMax = max;

    max = guess - 1;
    NextGuess();
}

void NextGuess()
{
    lastGuess = guess;

    guess = Random.Range(min, max+1);
    guessText.text = guess.ToString();
}

public void Back()
{
    guess = lastGuess;
    min = lastMin;
    max = lastMax;

    guessText.text = guess.ToString();
}
}

如果这不是您想要的,请写评论,我会编辑答案