Search code examples
c#urlunity-game-enginespriteunityscript

How to use WWW class to change the Sprite?


I'm struggling to change the sprite image to use WWW class in Unity.

I have a picture of a profile png on a website that I'd like to load in game. I'd like to change the Sprite of the Sprite Renderer attached to a game object so that the new sprite is that of personal profile.

I think that the IEnumerator can't be used with event, so I rearranged it like below. There is no error but it didn't work.

Please let me know how to do this.

using UnityEngine;
using System.Collections;
using System.IO;
using UXLib.User;
using UXLib.Connect;

public class UserImage : MonoBehaviour {
    UXAndroidManager androidManager;
    private SpriteRenderer spriteRenderer;
    public Material mat;


void Start(){
    spriteRenderer = GetComponent<SpriteRenderer> ();
    androidManager.StartGallery (LogIn.userId);

}

void Awake () {
    GameObject go = GameObject.Find ("AndroidManager");
    androidManager = go.GetComponent<UXAndroidManager> ();
    androidManager.InitAndroid ();

    androidManager.OnAnd_ProfileImageChanged += OnProfileImageChaned;
}

void OnDestroy() {
    androidManager.OnAnd_ProfileImageChanged -= OnProfileImageChaned;
}

void OnProfileImageChaned(string filePath) {
    UXPlayerController player = UXPlayerController.Instance;
    player.ChangeProfileImage(filePath);

    string logString = player.GetLastReceivedData();

    ProfileImage (filePath);

}
IEnumerator ProfileImage(string filePath){
    WWW www = new WWW (filePath);
    yield return www;


    SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
    Sprite sprite = new Sprite();
    sprite = Sprite.Create(www.texture, new Rect(0, 0, 170, 170),new Vector2(0, 0),100.0f);

    renderer.sprite = sprite;
    renderer.material = mat;
}
}

Solution

  • Call ProfileImage in a Coroutine.

    A coroutine is a function that can suspend its execution (yield) until the given given YieldInstruction finishes.

    So, just change the call in OnProfileImageChaned from:

    ProfileImage (filePath);

    to:

    StartCoroutine(ProfileImage(filePath));

    I would also recommend to take a look at the unity docs for coroutines: http://docs.unity3d.com/ScriptReference/Coroutine.html http://docs.unity3d.com/Manual/Coroutines.html