首页 > 解决方案 > 请求时未加载下一个场景

问题描述

我创建了一个游戏,当用户打破所有块时,他会被带到下一个场景,但是尽管添加了我在构建设置中拥有的所有场景,但这并没有发生。我没有任何错误,场景写得正确。有人可以帮我解决这个问题吗?

这是构建设置 在此处输入图像描述

砖脚本:(调用场景的地方)

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

public class Bricks : MonoBehaviour {

public LevelManager myLevelManager;
public static int brickCount = 0;
public int maxNumberOfHits = 0;
int timesHit;
public AudioClip BlockBreaking;

// Use this for initialization
void Start () {

    timesHit = 0;

    if(this.gameObject.tag == "BrickHit")
    {
        brickCount++;

    }

    if(this.gameObject.tag == "BrickHitTwice")
    {
        brickCount++;
    }
}

void OnCollisionEnter2D()
{
    timesHit++;

    if (timesHit == maxNumberOfHits)
    {
        brickCount--;
        Destroy(this.gameObject); 
    }

    if(brickCount == 0)
    {
        myLevelManager.LoadLevel("Level1.2"); //THIS SCENE IS NOT LOADING
    }

    if(this.gameObject.tag == "BrickHit") //If the gameObject (Block One Point) with the tag "BrickHit" is hit
    {
        Scores.scoreValue += 1;//The user will be rewarded 1 point
        AudioSource.PlayClipAtPoint(BlockBreaking, transform.position);
    }

    if(this.gameObject.tag == "BrickHitTwice") //If the gameObject (Block Two Points) with the tag "BrickHitTwice" is hit
    {
        Scores.scoreValue += 2; //The user will be rewarded 2 points
        AudioSource.PlayClipAtPoint(BlockBreaking, transform.position);
    }   
}

级别管理器脚本:

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

public class LevelManager : MonoBehaviour {
    public void LoadLevel(string name)
    {
       print("Level loading requested for" + name);
       SceneManager.LoadScene(name);
    }

标签: c#unity3d

解决方案


我怀疑您的错误可能在于您在Destroy()加载下一个场景之前正在调用游戏对象;您将获得先完成的比赛条件;LoadScene 或 Destroy() - 这可以解释为什么它有时会起作用。在理解你的问题之前,你永远不应该假设它是框架中的一个错误。

尝试将 Destroy() 放在 LoadScene() 之后或延迟以了解这是否是您的问题。


此外,您的 LevelManager 可以设为静态并且不需要从 MonoBehaviour 继承,因为它不使用 gameObject 功能。

public static class LevelManager {
    public static void LoadLevel(string name)
    {
       print("Level loading requested for" + name);
       SceneManager.LoadScene(name);
    }
}

使用LevelManager.LoadLevel("MyLevel");do ,但你可能会质疑什么更有效,使用 LevelManager.LoadLevel 或 SceneManager.LoadLevel,因为它们会做完全相同的事情。


推荐阅读