【问题标题】:Unity3D how to change sprite in SpriteRenderer at runtime with programaticly generated spriteUnity3D如何在运行时使用编程生成的精灵更改Sprite Renderer中的精灵
【发布时间】:2021-09-02 19:58:30
【问题描述】:

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

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

【问题讨论】:

    标签: c# unity3d sprite


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多