Hi,
First off, I want sure if this is applicable for the UI or Scripting sections in the forum, but here goes:
This might be a silly question, but I am trying to change the texture in my UI/HUD’s RawImage element.
After a lot of googling and trying, the only thing I got working was the following code:
Although it seems to work fine, I got mixed feelings when I needed to import UnityEditor for the AssetDatabase to work.
All I’m wondering about is if this is a valid way to load an image and use that as a RawImage texture?
For some reason it doesn’t feel entirely right to me.
Would love to hear some feedback on this, thanks so far.
Alternately you can get the byte stream of the image and create a new Texture2D from it. This is also how you use it for images downloaded from the web with www
public Sprite otherSprite;
public Texture2D otherTexture;
void Start () {
Invoke ("ChangeTexture", 1f);
}
void ChangeTexture()
{
//use this if its texture2D
Vector2 pivot = new Vector2(0.5f, 0.5f);
Rect tRect = new Rect(0,0, otherTexture.width, otherTexture.height);
GetComponent<Image>().overrideSprite = Sprite.Create( otherTexture, tRect, pivot);
//use this if its sprite
GetComponent<Image>().overrideSprite = otherSprite;
}
That is an interesting way of creating a sprite from a texture @psyydack
Although I’d have to wonder why you would (apart from avoiding issues with the RawTeture UI Component )
I know this is an old post, but Im having a similar issue.
In my case I am trying to change the movieTexture on my Raw Image when I press a button. I have a few buttons and a few videos, Im trying to make it so that if I press button A then video A plays, button B video B plays and so on.
I have the following code which I have added to every button, on the inspector I have given each button a different video to play. But the only video that will play is the one that is originally a movie texture of the raw image (video A) so I click button A the video plays fine, but if I press button B nothing happens, the movie texture doesn’t change and nothing plays
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class VideoController : MonoBehaviour
{
public MovieTexture video;
public void OnMouseDown()
{
GetComponent<Renderer>().material.mainTexture = video as MovieTexture;
if (!video.isPlaying)
{
video.Stop();
}
video.Play();
}
void Update()
{
}
}