首页 > 解决方案 > 在我的记忆卡游戏中上传时,如何让精灵图像保持不变?

问题描述

我在 Unity2d 中做一个记忆卡游戏。基本上,用户必须获得总共 8 场比赛才能赢得比赛。我的游戏功能齐全,我正在努力让它充满活力。我可以上传自己的图像并将其加载到游戏中。但是,游戏中的图像未正确调整大小。

这是我上传到游戏时的图像。

这是我想要的图片

我用于上传的代码是

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using SFB;
using UnityEngine;

public class OpenFileHelper : MonoBehaviour
{
    public static List<Texture2D> LoadImage()
    {
        var extensions = new[] {
            new ExtensionFilter("Image Files", "png", "jpg", "jpeg" )
        };

        var paths = StandaloneFileBrowser.OpenFilePanel("Select Images", "", extensions, true);//StandaloneFileBrowser.OpenFilePanel("Select Images", "", extensions, true);
        //System.IO.File.ReadAllLines(Application.persistentDataPath + "/Settings.txt")
        var textureList = new List<Texture2D>();

        foreach (var path in paths)
        {

            byte[] imageByte = File.ReadAllBytes(path);

            Texture2D texture = new Texture2D(2, 2);
            texture.LoadImage(imageByte);

            textureList.Add(texture);
        }
        //textureList.Resize(60, 60);
        //textureList.Apply();


        return textureList;
    }
}

我使用了这个家伙在 GitHub 中创建的自定义打包: https ://github.com/gkngkc/UnityStandaloneFileBrowser

我用来将图像更改为精灵的代码如下:

.
.
.
    public List<Texture2D> textures;
.
.
    private float width;
    private float height;
.
.
void initializeCards()
    {
        OpenFile();

        .
        .
 
    }
.
.
public void OpenFile()
    {
        textures = OpenFileHelper.LoadImage();
        if (!_init)
        {
            _init = true;
        }
}
.
.
    public Sprite getCardFace(int i)
    {
        width = 101;
        height = 180;
        
        Sprite sp = Sprite.Create(textures[i - 1], new Rect(0, 0, width, height), new Vector2(0.5f, 0.0f), 1.0f);
        return sp;
        
    }

我试图在我textures.widthtextures.heightSprite.Create 代码中做。但是,当我使用这些时,我会收到 CS1061 错误。

任何建议将不胜感激!

标签: c#unity3d

解决方案


Welltextures是 a List<Texture2D>of multipleTexture2D并且确实没有widthor height。但是一个Texture2D有;)

你可能应该使用

public Sprite getCardFace(int i)
{
    var tex = textures[i - 1];
    var sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.one * 0.5f, 1.0f);
    return sp;
}

推荐阅读