In this recipe, we will load an external image file and display it on the screen using the Unity Default Resources file (a library created at the time the game is compiled).
This method is perhaps the simplest way to store and read external resource files. However, it is only appropriate when the contents of the resource files will not change after compilation since the contents of these text files are combined and compiled into the resources.assets
file.
The resources.assets
file can be found in the Data
folder for a compiled game.
In the 0423_07_01
folder we have provided the following for this recipe: an image file, a text file, and an audio file in Ogg format:
externalTexture.jpg
cities.txt
soundtrack.ogg
Resources
.externalTexture.jpg
file and place it into the Resources
folder.// file: ReadDefaultResources.cs using UnityEngine; using System.Collections; public class ReadDefaultResources : MonoBehaviour { public string fileName = "externalTexture"; private Texture2D externalImage; private void Start () { externalImage = (Texture2D)Resources.Load(fileName); } private void OnGUI() { GUILayout.Label(externalImage); } }
Resources
folder, then in the Inspector view, change the public filename to the name of your image file and play the scene again. The new image should now be displayed.The Resources.Load(fileName)
statement makes Unity look inside its compiled resources.assets
project data file for the contents of file named externalTexture
. The contents are returned as a texture image, which is stored in the externalImage
variable. Our OnGU()
method displays externalImage
as Label()
.
Here are some details you don't want to miss.
You can load external text files using the same approach. The private variable needs to be a String (to store the text file contents). The Start()
method uses a temporary TextAsset
object to receive the text file contents, and the text
property of this object contains the String contents to be stored in the private variable:
public class ReadDefaultResources : MonoBehaviour { public string fileName = "textFileName"; private string textFileContents; private void Start () { TextAsset textAsset = (TextAsset)Resources.Load(fileName); textFileContents = textAsset.text; } private void OnGUI() { GUILayout.Label(textFileContents); } }
You can load external audio files using the same approach. The private variable needs to be an AudioClip
object:
// file: ReadDefaultResources.cs using UnityEngine; using System.Collections; [RequireComponent (typeof (AudioSource))] public class ReadDefaultResources : MonoBehaviour { public string fileName = "soundtrack"; private AudioClip audioFile; void Start (){ audio.clip = (AudioClip)Resources.Load(fileName); if(!audio.isPlaying && audio.clip.isReadyToPlay) audio.Play(); } private void OnGUI () { if(GUILayout.Button("Play")){ audio.Play(); } if(GUILayout.Button("Pause")){ audio.Pause(); } if(GUILayout.Button("Stop")){ audio.Stop(); } } }
3.12.166.131