如何通过点击统一调用一个类

时间:2014-05-29 05:08:27

标签: c# unity3d

我想创建一个带有yes和no按钮的对话框。所以我使用了gui.window并创建了一个脚本。但是现在我想在后退按钮上调用这个脚本。

toast.cs

void OnGUI()
{
    if (GUI.Button (new Rect (10, 350, 70, 20), "Back ")) 
    { 

    }
}

dialog.cs

public class dialog : MonoBehaviour
{
    public GUIStyle mystyle;
    public  Rect windowRect = new Rect (150, 80, 200, 100) ;

    public  void OnGUI ()
    {
        windowRect = GUI.Window (0, windowRect, WindowFunction, "Save !!!");
    }

    public  void WindowFunction (int windowID) 
    {
         GUI.Label( new Rect( 40, 40, 120, 50 ), "Do you want to save ?? ",mystyle  );
       if (GUI.Button (new Rect (10, 70, 70, 20), "Yes ")) 
       { 
           Application.LoadLevel("Settings");
       }

       if (GUI.Button (new Rect (120, 70, 70, 20), "No ")) 
       { 
           Application.LoadLevel("Settings");   
       }
    }
}

2 个答案:

答案 0 :(得分:1)

你可以做到

//This will add the dialog, so, And now the window will show up!
gameObject.AddComponent<dialog>();

由于您的对话框脚本是MonoBehaviour,您必须将其添加到对象以显示它。

并且,您必须选中“否”选项,它会给出与“是”相同的结果:P

你可以做一个

//This will remove the dialog, so, I will no longer see the window =)
gameObject.RemoveComponent<dialog>();

这就是你想要的吗? :)

答案 1 :(得分:0)

你可以试试这个:

<强> toast.cs

void OnGUI() {
       if (GUI.Button (new Rect (10, 350, 70, 20), "Back ")) 
       { 
            new dialog().OpenGUI();
       }
}

<强> dialog.cs

public class dialog : MonoBehaviour {
    public GUIStyle mystyle;
    public  Rect windowRect = new Rect (150, 80, 200, 100) ;

    public  void OnGUI () {
       OpenGUI();
    }

    public void OpenGUI(){
       windowRect = GUI.Window (0, windowRect, WindowFunction, "Save !!!");
    }

    public  void WindowFunction (int windowID) {
         GUI.Label( new Rect( 40, 40, 120, 50 ), "Do you want to save ?? ",mystyle  );
       if (GUI.Button (new Rect (10, 70, 70, 20), "Yes ")) 
       { 
         Application.LoadLevel("Settings");
       }

       if (GUI.Button (new Rect (120, 70, 70, 20), "No ")) 
       { 
         Application.LoadLevel("Settings");   
       }
    }

 }


这只是常识,你可能想看看Unity Answers他们能够在StackOverflow中提供更多的帮助