Search code examples
unity-game-enginetextures

How to set image on Texture in Unity 3d


I am new to Unity 3D and I want to do just little task: to set image on a Texture instance in Unity 3D. I don't know how to do this at runtime, and I also would like to know how I set its transparency low.

I don't need Texture2D - I just need Texture. My image is in .png format. I also want set an image from my documents directory on to this texture.


Solution

    • First import your image into your project by simply dropping it in your project window.

    • Select the image once it's in the project window and make sure that it is set to a Texture Type of Texture in your inspector.

    • Next, create a new material by right clicking in your project window.

    • Next you want to assign your image to this material and you can go about doing this by dragging and dropping your image (which is in the project window) on to your newly created material. In recent versions of Unity, you will need to drop it on the square to the left of "Albedo".

    • Then click on the new material and in your inspector window it should show you that your image is the active texture and the shader should be set to diffuse by default.

    • To activate transparency you'll want to change the shader type by clicking on the shader drop down menu in the inspector window and selecting Transparent/Diffuse (or any of the transparency options depending on what look you're going for).

    • After this to change it's transparency, simply click on the main color swatch and there should be a new window that opens giving you all kinds of modifiers (with 4 horizontal sliders to adjust Red, Green, Blue & Alpha).

    • Adjust the Alpha slider to affect the transparency of your material.

    Now, whenever you need to make a call to your material at runtime (e.g if you wanted to change the texture applied to a gameobject), simply do so by using:

    renderer.material
    

    This will affect the material off the gameObject that the script is attached to. So for example, if you wanted to change the texture at runtime from script you could say:

    // Assign the texture exposed in the inspector the renderer's material
    
    var texture : Texture;
    renderer.material.mainTexture = texture;
    

    And if you wanted to change the alpha channel:

    renderer.material.color.a = 0 // For example
    

    Hope this helps. Let me know if anything needs clarifying.