从一个场景重定向到另一个Unity 3D脚本

时间:2017-12-07 10:16:22

标签: c# unity3d buttonclick assetbundle

我有2个场景,我想在按钮点击时从一个场景重定向到另一个场景。我使用了AssetBundle。 以下是资产出口的代码:

public class ExportAssetBundles
{
    [MenuItem("Assets/Build AssetBundle")]
    static void ExportResource()
    {
        string folderName = "AssetBundles";
        string filePath = Path.Combine(Application.streamingAssetsPath, folderName);

        BuildPipeline.BuildAssetBundles(filePath, BuildAssetBundleOptions.None, BuildTarget.NoTarget);
    }
}

以下是加载代码:

public class RedirectToMenu : MonoBehaviour {
    void Start () {
        Button btn = GetComponent<Button>);
        btn.onClick.AddListener(OnClick);
    }

    public void OnClick(){
        Debug.Log("You have clicked the button!");
        LoadAsset("MenuFinal");
    }

    IEnumerator LoadAsset(string assetBundleName)//, string objectNameToLoad)
    {
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles");
        filePath = System.IO.Path.Combine(filePath, assetBundleName);

        var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(filePath);
        yield return assetBundleCreateRequest;

        AssetBundle asseBundle = assetBundleCreateRequest.assetBundle;
    }
}

所以当我在Unity中运行我的场景时,我在控制台中遇到了这样的错误:

ArgumentException: The output path "D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles" doesn't exist(at ExportAssetBundles.ExportResource () (at Assets/ExportAssetBundles.cs:16)

我已将我的场景放入Assets文件夹:

enter image description here

另外,我已将它们添加到Build settings:

enter image description here

那么如何修复此错误并使重定向工作?这是代码问题还是某些文件位置问题?

2 个答案:

答案 0 :(得分:2)

使用SceneManager.LoadScene()

public static void LoadScene(int sceneBuildIndex, 
                   SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);
public static void LoadScene(string sceneName, 
                   SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);

答案 1 :(得分:1)

您要求的路径是

"D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles"

但你真正的道路是

"D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundle" <- no 's'