Unity 场景加载时间非常长

我对 Unity 还很陌生,所以对 IDE 没有太多经验。我正在开发一个非常基本的应用程序、一个登录和一个带有一些基本 UI 元素的仪表板。


我遇到的问题是当我尝试切换场景时。因此,从 LoginScene 到 Dashboard 场景最多可能需要 20 秒。脚本甚至不需要运行太多逻辑。在我看来,这太长了,有人知道如何优化我的代码,或者至少知道我做错了什么?


这是检查正确用户和更改场景的代码。


// Start is called before the first frame update

void Start()

{

    Screen.orientation = ScreenOrientation.Portrait;

}


// Update is called once per frame

void Update()

{

    //get values from inputfields

    emailString = email.GetComponent<InputField>().text;

    passwordString = password.GetComponent<InputField>().text;


    btnLogin = login.GetComponent<Button>();

    btnLogin.onClick.AddListener(ValidateLogin);

}


private void ValidateLogin()

{

    if (emailString.Trim() == "aa" && passwordString.Trim() == "aa")

    {

        print("login succeeded!");


        SceneManager.LoadScene(1);

    }

    else

    {

        print("wrong credentials");

    }


}

顺便说一句:数字 1 是对我的下一个场景的引用,即仪表板场景。


阿波罗的战车
浏览 275回答 2
2回答

MMMHUHU

GetComponent<>()是一项资源密集型任务,并且您不必要地调用其中的 3 个,您还每帧添加一个事件侦听器。您应该做的是:阅读 Update、Awake、Start 所做的事情,然后删除该GetComponent<>()部分并改用属性或字段,并且不要每帧都添加事件侦听器。InputField emailInputField;InputField passwordInputField;Button loginButton;// Setting up the Scenevoid Awake(){&nbsp; &nbsp; emailInputField = email.GetComponent<Inputfield>();&nbsp; &nbsp; passwordInputField = password.GetComponent<InputField>();&nbsp; &nbsp; loginButton = login.GetComponent<Button>();&nbsp; &nbsp; loginButton.onClick.AddListener(ValidateLogin);}// Start is called before the first frame updatevoid Start(){&nbsp; &nbsp; Screen.orientation = ScreenOrientation.Portrait;}// Update is called once per framevoid Update(){&nbsp; &nbsp; //get values from inputfields&nbsp; &nbsp; emailString = emailInputField.text;&nbsp; &nbsp; passwordString = passwordInputField.text;}private void ValidateLogin(){&nbsp; &nbsp; if (emailString.Trim() == "aa" && passwordString.Trim() == "aa")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; print("login succeeded!");&nbsp; &nbsp; &nbsp; &nbsp; SceneManager.LoadScene(1);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; print("wrong credentials");&nbsp; &nbsp; }}

慕的地6264312

转换我的评论:Listener 被添加到 中Update(),而不是Start().&nbsp;因此,它被分配到每一帧。
打开App,查看更多内容
随时随地看视频慕课网APP