【问题标题】:Unity Number Wizard Back ButtonUnity Number 向导返回按钮
【发布时间】:2018-08-31 20:35:40
【问题描述】:

我刚刚创建了一个数字游戏,女巫会猜出你在想什么数字,并将其作为 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

【问题讨论】:

    标签: c# unity3d 2d


    【解决方案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();
    }
    }
    

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

    【讨论】:

    • 我试过了,但是由于某种原因,当我点击更高、更高、后退、更低之类的东西时,它会显示一个更高的数字,但应该显示一个更低的数字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多