- Home /
Create Texture2D and assign image to it through a script
Im trying to develope a system where if i enter the name of a texture i have in my assets folder, i can create a texture2d object and apply the string name to that object and have it find and apply the image in my assets folder to it.
Where im getting stuck is, when im trying to define the Texture2D asset in my script, i cant just say something like this:
var showImage : boolean = true; var stringForNewImageToBeDisplayed : String = "myImage"; //this string will be changing through an XML script periodically var currentImage : Texture2D; //the Texture that im trying to update
function showImageOverlay() { if(showImage) { //where im trying to assign the name of an image i have in my asset folder currentImage = stringForNewImageToBeDisplayed; } }
function OnGUI() { //shows image on screen GUI.DrawTexture (Rect (Screen.width*.1, (Screen.height/2)-(((Screen.width*.8)/1.6)/2)-20, Screen.width*.8, (Screen.width*.8)/1.6), currentImage);
}
This seems like it should be pretty simple but i dont know my way around JavaScript well enough to figure it out. Am i close? Thanks very much for any tips you can give me here!
Answer by qJake · Jun 14, 2010 at 10:21 PM
In Unity you don't access textures by name, you access them through references. This not only speeds up game performance, but it minimizes the size of the compiled game because non-used assets are not included.
Typically what you would do is create a public variable in your script, and then assign its value through the Inspector. You can even have arrays of assets if you choose.
The only way to call an asset by name is to place it inside the special folder Resources/. Any asset inside this folder is automatically included in the game, no matter what (even if you don't use it), so using the Resources folder to load assets exclusively is somewhat dangerous.
Any asset you place inside the Resources folder can be accessed by its name, like this:
var myTexture = Resources.Load("myImage");
but remember that anything you want to call by name needs to be in the Resources/ folder. The preferred way of retrieving assets is by reference through the Inspector, but if this absolutely does not work for you, you can use Resources.Load();
.
Read more about Resources.Load();
here:
http://unity3d.com/support/documentation/ScriptReference/Resources.html
Thank you for your answer, this is exactly what i needed. I understand now that its not the ideal way to call objects, but im trying to make this part of my script as modular as possible where by changing out scripts it will adjust the file. using the inspector is how i was doing it before but has become too time consu$$anonymous$$g and tedious. This should work great, thanks!