I need to change background image in unity 2D to a user-specified image while game is runing with C# script. The user will input the image file path.
filePathInput
and Image game object you wanna change backgroundImage
to the scriptChangeBackground
function to the OnClick event of the button.Here is the script. It uses an IEnumerator
so that you can call the function from the main thread without freezing the game for a while.
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.Collections;
public class BackgroundChanger : MonoBehaviour
{
public InputField filePathInput; // Input field for file path
public Image backgroundImage; // Image component to change background
public void ChangeBackground()
{
string filePath = filePathInput.text;
if (string.IsNullOrEmpty(filePath))
{
print("File path is empty");
return;
}
StartCoroutine(LoadImage(filePath));
}
private IEnumerator LoadImage(string filePath)
{
filePath = "file:///" + filePath;
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(filePath))
{
yield return uwr.SendWebRequest();
if (uwr.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error loading image: " + uwr.error);
}
else
{
Texture2D texture = DownloadHandlerTexture.GetContent(uwr);
Sprite newSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
backgroundImage.sprite = newSprite;
}
}
}
}