- Home /
How to get a Texture asset that is in the project and pass it to a function?
For example, I have a function which takes in a Texture
function ClearTexture(tex : Texture2D)
{
// blah blah blah
}
And I have a texture named "Canvas" in my project. Is there any code I can use to get that texture and pass it to my function, hypothetically something like this?
ClearTexture(FindTextureByName("Canvas"));
Edit: The texture is not attached to any game object or part of any models. It just exists in the project's Assets folder.
Answer by KvanteTore · Mar 25, 2010 at 09:28 AM
I believe assets has to be attached to a game component somehow, otherwise it will not be included in the built game. On the component you are creating, you could create an array of textures, and assign the possible textures to the elements in the array.
In C#:
Texture2D Textures[];
Texture2D FindTexture(string name) { foreach (Texture2D tex in Textures) { if (tex.name == name) { return tex; } } return null; }
If you don't want to attach the textures to the component, an alternative is to add the textures to a resource folder, and Resource.Load to load the texture
Answer by Hardcore Games · May 21, 2013 at 07:49 PM
You may also want to use this: Resources.LoadAssetAtPath
Link here: http://docs.unity3d.com/Documentation/ScriptReference/Resources.LoadAssetAtPath.html
Answer by gabobernal · Sep 08, 2017 at 02:38 PM
You can create a public variable in your script, for example:
public class MyScript : MonoBehaviour {
public Texture2D myTexture;
}
then you can bind the texture to the script by selecting the script from the assets panel and configuring the desired target in the myTexture custom field