In my game I wanted to allow the player to choose their own avatar by uploading a local file. I couldn’t get my idea to work. Fortunately I found this answer which did work, but now I’m curious why mine did not.
My idea was to use File.Copy to copy the desired file from the user’s hard drive to the game’s Resources folder, and then use Resources.Load to load the file as a Texture2D object. Here’s an example:
using UnityEngine;
using System.Collections;
using System.IO;
public class Test : MonoBehaviour {
public GameObject _avatar;
void Start () {}
void Update () {}
void OnGUI() {
if (GUI.Button (new Rect (710, 200, 75, 30), "Load")) {
File.Copy(@"C:\PATH_TO_FILE\avatar.gif", @"C:\PATH_TO_GAME\Resources\avatar.gif", true);
}
if (GUI.Button (new Rect (600, 250, 75, 30), "Create")) {
var tex = Resources.Load<Texture2D> ("avatar");
_avatar= new GameObject ("AvatarObject", new System.Type[]{typeof(SpriteRenderer)});
var spr = Sprite.Create (tex, new Rect (0f, 0f, 128, 128), new Vector2 (0.5f, 0.5f));
_avatar.GetComponent<SpriteRenderer> ().sprite = spr;
}
}
}
I verified that clicking the “Load” button does copy the correct file to the correct location. However, when I then click the “Create” button, nothing happens. When I pause in the editor, I can see that the gameobject was created, but the “sprite” field in the Sprite Renderer says “None,” as if the file doesn’t exist. If I stop playing and start again and click “Create” again, the same thing happens. However, if I stop playing and force the editor to Refresh the assets and then restart and click “Create,” it does work.
Why is this?