Unity3D如何在运行时使用以编程方式生成的精灵更改精灵渲染器中的精灵

Unity3D how to change sprite in SpriteRenderer at runtime with programaticly generated sprite

我在 Unity3D 项目中遇到精灵问题。基本上我无法在运行时更改 SpriteRenderer 组件中的精灵。在我的研究过程中,我只看到了要求您预加载精灵的解决方案,但我不能,因为它是根据用户输入的图像生成的。 所以发生的事情是用户可以通过从他的计算机输入他自己的照片来改变“游戏”的背景。我把照片和所有东西都放进去,然后从中生成一个精灵,但是当我用他的精灵改变基本精灵时,没有任何反应。基本精灵仍在显示。如果我将背景精灵放在 canvas 中面板的图像上,那么一切都很好,但是如果我对 SpriteRenderer 做同样的事情,那么什么也不会发生。这是我的代码:

public class UploadImage : MonoBehaviour
{
    public GameObject background;
    public Sprite sp;
    [DllImport("__Internal")]
    private static extern void ImageUploaderCaptureClick();

    public void setTexture(Texture2D texture)
    {
        sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(texture.width / 2, texture.height / 2));
        background.GetComponent<SpriteRenderer>().sprite = sp;
    }


    IEnumerator LoadTexture(string url)
    {
        WWW image = new WWW(url);
        yield return image;
        Texture2D texture = new Texture2D(1, 1);
        image.LoadImageIntoTexture(texture);
        Debug.Log("Loaded image size: " + texture.width + "x" + texture.height);
        setTexture(texture);
    }

    void FileSelected(string url)
    {
        StartCoroutine(LoadTexture(url));
    }

    public void OnButtonPointerDown()
    {
#if UNITY_EDITOR
        string path = UnityEditor.EditorUtility.OpenFilePanel("Open image", "", "jpg,png,bmp");
        if (!System.String.IsNullOrEmpty(path))
            FileSelected("file:///" + path);
#else
        ImageUploaderCaptureClick ();
#endif
    }
}

我无法在 canvas 中的图像上设置背景,因为其他游戏对象会失去透明度,而且如果我将图像上的 alpha 设置得太低,那么当游戏对象移动时,一切都会变得模糊。 感谢您的帮助

我认为您在生成精灵时将精灵轴设置错误。您的精灵现在甚至应该显示,但它远离您期望的位置。

将您的代码更改为如下内容:

sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));