Answer by VisualTech48 · Jan 13, 2017 at 12:02 AM
What are you trying to achieve? To take the Texture, out of the Raw Image component and to place it/use it as a Texutre2D?
Its pretty easy actually:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Switch_Image : MonoBehaviour {
public RawImage Test;
public Texture2D TheTexture;
void Start () {
TheTexture = Test.texture as Texture2D;
}
You can always try to use as Something in this case as Texture2D that will try to convert it. In this case it works.
Try a cast ins$$anonymous$$d, like :
TheTexture = (Texture2D) Test.texture;
You should get an earlier and more detailed exception.
You have to assign the RawImage component to the script...
I try this too,Test.texture is not null but TheTexture is null
Try this:
private Texture2D TextureToTexture2D(Texture texture)
{
Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
RenderTexture currentRT = RenderTexture.active;
RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
Graphics.Blit(texture, renderTexture);
RenderTexture.active = renderTexture;
texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture2D.Apply();
RenderTexture.active = currentRT;
RenderTexture.ReleaseTemporary(renderTexture);
return texture2D;
}
Answer by Max-Bot · Jan 07, 2019 at 09:14 PM
Unity 2018+
public static class TextureExtentions
{
public static Texture2D ToTexture2D(this Texture texture)
{
return Texture2D.CreateExternalTexture(
texture.width,
texture.height,
TextureFormat.RGB24,
false, false,
texture.GetNativeTexturePtr());
}
}
Usage:
Texture2D texture2D = your_texture.ToTexture2D();
Answer by twinkle1087 · Jun 08, 2018 at 09:15 AM
You can print the type of your RawImage.texture. Maybe the type is rendertexture. You may need more steps to convert to Texture2d.
Your answer
![](https://koobas.hobune.stream/wayback/20220612104714im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to load a folder of textures automatically to an array of Raw Images? 2 Answers
How can I reset the score counter? 0 Answers
Unity WebCamTexture looks squashed in RawImage 0 Answers
Texture file is all alpha when resizing 0 Answers
Better way to edit RawImage texture data?,Better way to edit a RawImage texture? 0 Answers