Hello, I wanted to know how I could load an image from my computer for a sprite.
For now, with this script (not mine), I can open the explorer, select an image and set it to a raw image (in game) :
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
public class OpenImagesplz : MonoBehaviour
{
string path;
public RawImage image;
[System.Obsolete]
public void OpenExplorer()
{
path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");
GetImage();
}
[System.Obsolete]
void GetImage()
{
if (path != null)
{
UpdateImage();
}
}
[System.Obsolete]
void UpdateImage()
{
WWW www = new("file:///" + path);
image.texture = www.texture;
}
public void ResetImage()
{
image.texture = null;
}
}
I thought of putting spriteRenderer.sprite = www.texture; but it doesn’t work
You should change the image to sprite first . You can do that by selecting the image and in the inspector section. You can see Texture Type change it to Sprite(2D and Ui) and hit apply Then you can use it as a sprite
Thanks for answering but I don’t want this. When you play, there’s a button which opens the explorer (with the fonction “OpenExplorer();”) and you select the image you want to apply to the raw image. But I also want to apply it to a sprite
As you are using UnityEditor; namespace, none of this will work in a build. The above code will only work within the Unity editor in front of you.
Why are you rewriting such basic functionality? Just use the in-built texture import process, and as Shaky Sam points out above, set it to import as a sprite and move on. There is no need to write code for something as basic as this.
If you intend for this code to run in the final build (eg, for your customer to do it), start with any one of the thousands of tutorials on reading images at runtime, then when you have that working and have a Texture2D at runtime, use Sprite.Create() to make a sprite out of it.
NOTE: Nothing in a final game will EVER use the UnityEditor namespace.
If you intend for this code to run in the final build (eg, for your customer to do it), start with any one of the thousands of tutorials on reading images at runtime, then when you have that working and have a Texture2D at runtime, use Sprite.Create() to make a sprite out of it.
Yeah, I thought that would work in the final build… Anyways I will check out on ‘reading images at runtime’. I’ll post the solution here if I find it. Thanks for the advice