简体   繁体   中英

Unity editor / standalone build crash when loading a small scene

I have a small scene setup with the UFPS asset from unity assetstore. When I load DIRECTLY the scene its working with less then 1 sec loading time, BUT when i load it from my menu the editor crashes. I also have a "loader" scene with the async method that one is working also so i think something went off with the button (I also try loading the async scene from menu and also try loading the game scene from menu crash each time) The same with builded versions I could't find ANY solutions. Here is the button's script (c#):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class ButtonEvents : MonoBehaviour
{
    [SerializeField]
    public int selected;
    public Button ok;

    void Start()
    {
        Button okbtn = ok.GetComponent<Button>();
        okbtn.onClick.AddListener(StartGame);

        
    }
    public void Quit()
    {
        Application.Quit();
    }
    

    public void markabreakdown()
    {
        selected = 1; 
    }



    void Update()
    {
        Button okbtn = ok.GetComponent<Button>();
        okbtn.onClick.AddListener(StartGame);
        Debug.Log(selected);


    }
    public void StartGame()
    {
        SceneManager.LoadScene(selected);
    }
}

Why do you use AddListener in Update -> adding a callback each and every frame?! When you click on that button you are trying to call the StartGame method hundreds of times depending how long you have spent in that scene.. and then most probably it tries to call that method the second time in a moment when the scene is already changed -> this button and this class already destroyed -> null ref exception.


Remove your entire Update method!

You already added the callback in Start


Further note that ok already is a Button so calling ok.GetComponent<Button>() is completely redundant. Simply do

void Start()
{
    ok.onClick.AddListener(StartGame); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM