Unity代码可在编辑器中使用,但不适用于Build(EXE文件)C#

时间:2018-07-15 11:55:12

标签: unity3d

我的代码加载外部图像并从中构建一个用于unity3d的SkyBox。 SkyBox的所有文件都在正确的路径上(手动复制)。

代码加载了6个外部图像,然后构建了一个SkyBox,我认为在构建状态中加载时存在问题。 (但不确定)

也许Unity阻止我这样做?

我没有错误或警告代码。这真的让我发疯了!!!

using System.IO;
using UnityEngine;

public class ChangeSkyBox : MonoBehaviour
{

public static Texture2D LoadPNG(string filePath)
{

    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists(filePath))
    {
        fileData = File.ReadAllBytes(filePath);
        tex = new Texture2D(1024, 1024);
        tex.LoadImage(fileData);
    }
    tex.wrapMode = TextureWrapMode.Clamp;
    return tex;
}




public static Material CreateSkyboxMaterial(SkyboxManifest manifest)
{
    Material result = new Material(Shader.Find("RenderFX/Skybox"));
    result.SetTexture("_FrontTex", manifest.textures[0]);
    result.SetTexture("_BackTex", manifest.textures[1]);
    result.SetTexture("_LeftTex", manifest.textures[2]);
    result.SetTexture("_RightTex", manifest.textures[3]);
    result.SetTexture("_UpTex", manifest.textures[4]);
    result.SetTexture("_DownTex", manifest.textures[5]);

    return result;
}

private Texture2D[] textures;



private void Start()
{

    Texture2D xt1 = LoadPNG(Directory.GetCurrentDirectory() + "\\Assets\\SkyBox\\Front.png");
    Texture2D xt2 = LoadPNG(Directory.GetCurrentDirectory() + "\\Assets\\SkyBox\\Back.png");
    Texture2D xt3 = LoadPNG(Directory.GetCurrentDirectory() + "\\Assets\\SkyBox\\Left.png");
    Texture2D xt4 = LoadPNG(Directory.GetCurrentDirectory() + "\\Assets\\SkyBox\\Right.png");
    Texture2D xt5 = LoadPNG(Directory.GetCurrentDirectory() + "\\Assets\\SkyBox\\Top.png");
    Texture2D xt6 = LoadPNG(Directory.GetCurrentDirectory() + "\\Assets\\SkyBox\\Bottom.png");
    SkyboxManifest manifest = new SkyboxManifest(xt1, xt2, xt3, xt4, xt5, xt6);

    Material newMat = new Material(Shader.Find("RenderFX/Skybox"));
    newMat = CreateSkyboxMaterial(manifest);

    RenderSettings.skybox = newMat;

    DynamicGI.UpdateEnvironment();
}

}

public struct SkyboxManifest
{
    public Texture2D[] textures;

    public SkyboxManifest(Texture2D front, Texture2D back, Texture2D left, Texture2D right, Texture2D up, Texture2D down)
    {
        textures = new Texture2D[6]
        {
             front,
             back,
             left,
             right,
             up,
             down
        };
    }

}

1 个答案:

答案 0 :(得分:1)

我相信您的问题出在这条线上。

 Material result = new Material(Shader.Find("RenderFX/Skybox"));

Unity在运行时找不到它。要对其进行修复,请在Unity中手动制作“基础”材料,然后通过检查器将其附加到脚本中。