unity 动态加载图片成为精灵 显示在场景中

需求:将图片显示在场景中

做法:将图片转换成Sprite,然后显示在场景中

1、在Asserts文件下创建文件夹命名为Resources,听说Resources.Load()只能加载该文件夹下的图片;

2、首先判断图片是否存在;

2、创建GameObject,添加SpriteRender组件,完成。

public class create: MonoBehaviour
{
    
    void Start()
    {
        findPNG("depth.png");
    }

    public void findPNG(string vFileName)
    {
        string Path = "Assets\\Resources\\" + vFileName;
        if (File.Exists(Path))
        {
            createSprite(vFileName);
        }
    }
    public void createSprite(string vFileName)
    {
        string FileName = Path.GetFileNameWithoutExtension(vFileName);
        GameObject Object = new GameObject();
        Object.AddComponent();
        SpriteRenderer SpriteRender = Object.GetComponent();
        SpriteRender.name = "Mark";
        Texture2D Picture = (Texture2D)Resources.Load(FileName) as Texture2D;
        Rect Size = new Rect(0, 0, Picture.width, Picture.height);
        Vector2 Pivot = new Vector2(0, 0);
        SpriteRender.sprite = Sprite.Create(Picture, Size, Pivot);
        //需要修改
        Object.transform.position = new Vector3(0, 0, 0);
    }
}

 

你可能感兴趣的:(unity,unity)