如何使用SetActive()

时间:2017-03-14 18:39:12

标签: c# unity3d unity2d

我正在尝试创建注册场景。我想在用户输入无效的名称,电子邮件和/或密码时显示三个面板。我在开始时隐藏了面板。这样可行。但是,当我输入无效信息并单击按钮时,面板不会显示。如果validNamevalidEmailvalidPassword为false,则会进入ShowNamePanel()并卡住。

我的代码出了什么问题?

public GameObject namePanel;
public GameObject emailPanel;
public GameObject passwordPanel;

public void Start ()
{
    HideNamePanel ();
    HideEmailPanel ();
    HidePasswordPanel ();
}

public void ButtonClick ()
{
    Debug.Log ("1. Button clicked.");

    CreateUser ();
}

/*
 * Sends post request to create new user if name, email, and 
 * password are valid.
 */

public void CreateUser ()
{

    validName = IsValidName (username);
    validEmail = IsValidEmailAddress (email);
    validPW = IsValidPassword (password);
    //validNewUserCombo = IsValidNewUserCombo (email, password);

    if (validName && validEmail && validPW) {
        Debug.Log ("6. VALID INPUTS");
        CallAPI ();
    } else {
        Debug.Log ("8. INVALID INPUTS");
        if (validName == false) {
            ShowNamePanel ();
        }
        if (validEmail == false) {
            ShowEmailPanel ();
        }
        if (validPW == false) {
            ShowPasswordPanel ();
        }
    }
}

public void ShowNamePanel() {
    Debug.Log ("shownamepanel");
    namePanel.SetActive (true);
}

public void HideNamePanel() {
    namePanel.SetActive (false);
}

public void ShowEmailPanel() {
    Debug.Log ("showemailpanel");
    emailPanel.SetActive (true);
}

public void HideEmailPanel() {
    emailPanel.SetActive (false);
}

public void ShowPasswordPanel() {
    Debug.Log ("showpasswordpanel");
    passwordPanel.SetActive (true);
}

public void HidePasswordPanel() {
    passwordPanel.SetActive (false);
}

Connecting variables in the Inspector

Panel hirearchy

2 个答案:

答案 0 :(得分:1)

好的,所以你的问题是,当游戏对象处于非活动状态时,此游戏对象的所有脚本也停止工作。因此,如果您希望这样做,那么最好将脚本放在其他可在此过程中保持活动状态的内容上。

在你的情况下,当你设置活动(假)面板时,它们上的脚本也是无效的,所以它们不再运行。

这来自Unity Documentation

  

使GameObject处于非活动状态将禁用所有组件,关闭所有连接的渲染器,对撞机,刚体,脚本等......

答案 1 :(得分:0)

您需要告诉Unity您尝试禁用/启用哪些面板,例如:

public Panel panelToToggle;
private void Awake()
{
     // Gets the Panel component if there's one on the GameObject this
     // script is attached to
     panelToToggle = GetComponent<Panel>();
}
private void Start()
{
     // Sets the parent gameObject of the Panel component to inactive
     panelToToggle.gameObject.SetActive(false)
}
private void EnablePanel()
{
     // Sets the parent gameObject of the Panel component to active
     panelToToggle.gameObject.SetActive(true)
}