创建图片的Unity问题

时间:2018-10-27 06:52:12

标签: unity3d sprite

我不确定在这里做什么,我有代码行

Sprite newSprite = Sprite.Create(spriteTexture, 
    new Rect(0, 0, spriteTexture.width, spriteTexture.height), 
    new Vector2(0, 0), 
    pixelsPerUnit, 
    0, 
    spriteType);

对于那行代码,我会收到错误消息

  

NullReferenceException:对象引用未设置为对象的实例

我真的不知道我在这里做错了什么

Sprite NewSprite = new Sprite();

无法使用其构造函数,我确定自己很傻,但是我真的很感谢一些输入:)

编辑:遗漏我的代码的歉意:

public static class ImageToSprite
{

public static Texture2D LoadTexture(string filePath)
{
    Texture2D tex2D;
    byte[] fileData;

    if (File.Exists(filePath))
    {
        fileData = File.ReadAllBytes(filePath);
        tex2D = new Texture2D(2, 2);

        if(tex2D.LoadImage(fileData))
        {
            return tex2D;
        }
    }

    return null;
}

public static Sprite LoadNewSprite(string filePath, float pixelsPerUnit = 100.0f, SpriteMeshType spriteType = SpriteMeshType.Tight)
{
    Texture2D spriteTexture = LoadTexture(filePath);
    Sprite newSprite = Sprite.Create(spriteTexture, new Rect(0, 0, spriteTexture.width, spriteTexture.height), new Vector2(0, 0), pixelsPerUnit, 0, spriteType);

    return newSprite;
}

public static Sprite ConvertTextureToSprite(Texture2D texture, float PixelsPerUnit = 100.0f, SpriteMeshType spriteType = SpriteMeshType.Tight)
{
    // Converts a Texture2D to a sprite, assign this texture to a new sprite and return its reference

    Sprite NewSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0), PixelsPerUnit, 0, spriteType);

    return NewSprite;
}
}

这是我从以下位置获得此代码的链接:https://forum.unity.com/threads/generating-sprites-dynamically-from-png-or-jpeg-files-in-c.343735/

1 个答案:

答案 0 :(得分:0)

啊,我为自己的愚蠢而道歉,但问题很容易解决,我从loadtexture函数返回null,并且完全没有故障保护,我为浪费时间而道歉。