简体   繁体   中英

Unity 3d Change Texture after Build

I have a script attached to a Gameobject. I have also a button. When the button is pressed the file explorer opens and allow to select a custom image from PC and after importing original texture of Gameobject changes. But when I exit and run again then the custom texture replaces with original one. I want to save a custom texture instead of original texand then an option to delete the custom and go back to original tex. Please help me in this. Sorry for my bad english. This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System.IO;


public class ChangeTex : MonoBehaviour 

{
    string path;
    public MeshRenderer mRenderer;

    public void OpenExplorer()
    {
        path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");
        GetImage();
    }

    void GetImage()
    {
        if (path != null)
        {
            UpdateImage();
        }
    }
    void UpdateImage()
    {
        byte[] imgByte = File.ReadAllBytes(path);
        Texture2D texture = new Texture2D (2, 2);
        texture.LoadImage(imgByte);

        mRenderer.material.mainTexture = texture;

    }

}

The simple way is store path to your image in PlayerPrefs . It's a Platform-independent feature that allows you to put and get some player settings in device storage. Storing it in device storage allows you get your data after re-starting application.

To save your settings to storage You have to put it and save:

PlayerPrefs.SetString(IMAGE_PATH_KEY, path);

Getting settings:

if (PlayerPrefs.HasKey(IMAGE_PATH_KEY))
{
    path = PlayerPrefs.GetString(IMAGE_PATH_KEY);
}

Then instead of calling OpenExplorer() you can check your path in PlayerPrefs in Start() or Awake() first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM