在运行时加载图像的问题(Unity)(后期构建)

时间:2017-01-26 20:30:58

标签: c# image file unity3d runtime

我在Unity 5中创建一个Arcade GUI。我希望实现的主要功能是一个系统,可以自动为每个游戏(在文件结构中)创建按钮,并从未包含在构建中的文件中加载1个精灵和一些文本。我希望Arcade能够在与构建相同的文件夹中读取文件,而不必在构建中包含这些文件。这是我尝试过的一些代码:

DirectoryInfo DirectoryToFiles = new DirectoryInfo ("Games");
    DirectoryInfo[] Folders = DirectoryToFiles.GetDirectories ();
    foreach (DirectoryInfo Folder in Folders) {
        FileInfo[] Files = Folder.GetFiles ();
        string filename = Files [0].Name.Substring(0,Files [0].Name.IndexOf("."));

        //Loads Image
        Image = Resources.Load ("Games" + "/" + Folder.Name + "/" + filename + ".png") as Texture2D;
        ButtonSprite = Sprite.Create (Image, new Rect (0, 0, Image.width, Image.height), new Vector2 (0f, 0f));
        //The Declaration of "ButtonSprite" returns a NullReferenceException

        //Reads Description File
        GameDescription = ReadFile (Folder,filename);

        //Gives Path to Play Button
        GameObject.Find ("Play").GetComponent<PlayButton> ().UpdatePath ("Games" + "/" + Folder.Name + "/" + filename + ".exe");


        //Transfers All Variables to the new Button
        CurrentButton = Instantiate (GameButton, GameObject.Find ("Content").GetComponent<Transform> ());
        CurrentButton.GetComponent<Transform> ().localPosition = new Vector3 (x,0f,1f);
        x += 230;
        CurrentButton.GetComponent<ButtonInstantiate> ().UpdateVariables (ButtonSprite, GameName.Substring(0,GameName.IndexOf(".")), GameDescription, Hours);

This is what my Build file looks like.

This is what the File structure looks like

如果有人能让我知道我需要使用的具体方法,我将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

我认为问题出在以下几行:

    Image = Resources.Load ("Games" + "/" + Folder.Name + "/" + filename + ".png") as Texture2D;

使用Resources.Load时,您不会提供文件类型,只提供路径名称。此外,Image是Unity类型,可能会给您一个错误。如果你尝试它应该工作:

    Texture2D btnTexture = Resources.Load ("Games/" + Folder.Name + "/" + filename) as Texture2D;

编辑:但是,这将在Assets / Resources / Games / FolderName / FileName下的构建中查找目录。有关从外部目录加载纹理的更多信息,这可能有所帮助: http://answers.unity3d.com/questions/813495/can-i-load-textures-outside-the-resources-folder.html

为了清楚了解其他潜在读者,还有一些其他信息:您在Resources文件夹中放置的任何内容都将包含在构建中。如果你打算使用它们,建议只把东西放在构建中,否则它只占用额外的空间。

希望这有帮助!