At times, the contents of the external resource files may need to be changed after the game compilation. Hosting the resource files on the web may not be an option. There is a method of manually storing and reading files from the Resources
folder of the compiled game, which allows for those files to be changed after the game compilation.
The 1362_10_01
folder provides the texture image that you can use for this recipe:
externalTexture.jpg
To load external resources by manually storing the files in the Resources
folder, do the following:
using UnityEngine; using System.Collections; using UnityEngine.UI; using System.IO; public class ReadManualResourceImageFile : MonoBehaviour { private string fileName = "externalTexture.jpg"; private string url; private Texture2D externalImage; IEnumerator Start () { url = "file:" + Application.dataPath; url = Path.Combine(url, "Resources"); url = Path.Combine(url, fileName); WWW www = new WWW (url); yield return www; Texture2D texture = www.texture; GetComponent<Image>().sprite = TextureToSprite(texture); } private Sprite TextureToSprite(Texture2D texture){ Rect rect = new Rect(0, 0, texture.width, texture.height); Vector2 pivot = new Vector2(0.5f, 0.5f); Sprite sprite = Sprite.Create(texture, rect, pivot); return sprite; } }
externalTexture.jpg
image to your standalone's Resources
folder.You will need to place the files in the Resources
folder manually after every compilation.
When you create a Windows or Linux standalone executable, there is also a _Data
folder, created with the executable application file. The Resources
folder can be found inside this Data
folder.
A Mac standalone application executable looks like a single file, but it is actually a MacOS package
folder. Right-click on the executable file and select Show Package Contents. You will then find the standalone's Resources
folder inside the Contents
folder.
Note the need to use the System.IO
and UnityEngine.UI
packages for this recipe.
When the executable runs, the WWW
object spots that the URL starts with the word file, and so Unity attempts to find the external resource file in its Resources
folder, and then load its contents.
There are some details that you don't want to miss.
The filepath folder separator character is different for Windows and Mac file systems (backslash () for Windows, forward slash (
/
) for the Mac). However, Unity knows which kind of standalone you are compiling your project into, therefore the Path.Combine()
method will insert the appropriate separator slash character form the file URL that is required.
3.144.107.193