【问题标题】:It wont let me turn my button to be interactable from other script [closed]它不会让我把我的按钮变成可与其他脚本交互的[关闭]
【发布时间】:2017-06-24 12:01:09
【问题描述】:
最近我开始接触 Unity 并开始制作我的第一款游戏。我真的很高兴,但最近我真的很生气。
我在我的游戏中制作了一个关卡系统(一旦你完成了第一关(所有关卡都是单独的场景),你就可以进入下一个关卡)。我已经知道如何使用application.loadlevel 等。但我还想要关卡菜单(您可以在其中通过单击按钮选择过去的关卡或当前关卡)来打开的难处理性一旦你通过拿起一个立方体完成了上一个级别。不幸的是,我不知道该怎么做,因为我所有的脚本都失败了。
请帮助我并提前感谢,我是初学者,所以不要解释得太高级。只要告诉我该做什么以及我需要在我的脚本中写什么。如果我必须使用预制件,请告诉我这也让我感到困惑。
【问题讨论】:
标签:
c#
user-interface
unity3d
【解决方案1】:
首先,您需要保存已完成关卡的某个位置。此信息必须以持久的方式保存,否则,您的玩家每次启动游戏时都必须重新启动整个游戏。有很多方法可以做到这一点,但PlayerPrefs 可能是一个起点。
任何关卡完成后(在加载下一个场景之前),调用以下函数:
public void OnLevelCompleted()
{
// Retrieve name of current scene / level
string sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
PlayerPrefs.SetInt( sceneName, 1 ) ; // Indicates the level is completed
}
然后,在您的家庭场景中,使用以下代码将脚本附加到您的按钮:
public string SceneName ; // Indicate which level this button must load once you click on it. Be carefull, the name must be the same as in your Build Settings
protected void Awake()
{
UnityEngine.UI.Button button = GetComponent<UnityEngine.UI.Button>();
if( button != null )
{
// Make the button load the given scene
button.onClick.AddListener( () => UnityEngine.SceneManagement.SceneManager.LoadScene( SceneName ) ) ;
// Make the button interactable only if the given scene / level has been completed
button.interactable = PlayerPrefs.GetInt( SceneName ) > 0 ;
}
else
Debug.LogWarning("No button component attached", this ) ;
}