le0327
@le0327

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

UnityStandaloneFileBrowser

Unity で以下のコードを使用していますが、ファイルを選択するときに次の動作が発生します。この動作がなくなり、ボタンの押下ごとにファイルの選択が 1 回だけ行われるようになることを期待しています。

〜動作
(1) ファイル選択ダイアログが開き、ファイルが選択されます(キャンセル時も同様)。
(2) 再度ダイアログが開き、画像を4回選択するかキャンセルを押すまで閉じません。

〜実行環境
Unity 最新バージョン
Windows11

〜コード

using System.IO;
using UnityEngine;
using UnityEngine.UI;
using SFB; // StandaloneFileBrowserの名前空間

public class CardManager : MonoBehaviour
{
public Button extraButton;
public GameObject cardPrefab;
public InputField nameInputField;
public Transform scrollViewContent; // ScrollView内でカードの親になるオブジェクト
private string imagePath;
private string cardName;

void Start()
{
    // ExtraButtonがクリックされたときにOpenFileBrowserを呼び出す
    extraButton.onClick.AddListener(OpenFileBrowser);
}

void OpenFileBrowser()
{
    var extensions = new[] {
        new ExtensionFilter("Image Files", "png", "jpg", "jpeg")
    };

    // ファイルパネルを開いて1枚だけ選択
    string[] paths = StandaloneFileBrowser.OpenFilePanel("Select Image", "", extensions, false);

    // 選択されたパスが空でなく、1つ以上選択されている場合
    if (paths != null && paths.Length > 0 && !string.IsNullOrEmpty(paths[0]))
    {
        imagePath = paths[0];
        CreateCard();
    }
    else
    {
        Debug.LogWarning("画像が選択されませんでした。");
    }
}

void CreateCard()
{
    if (string.IsNullOrEmpty(imagePath))
        return;

    // 新しいカードを生成
    GameObject newCard = Instantiate(cardPrefab, scrollViewContent);

    // 選択した画像をテクスチャとして読み込む
    Texture2D texture = LoadTexture(imagePath);

    // テクスチャをカードのImageコンポーネントに適用する
    Image cardImage = newCard.GetComponent<Image>();
    cardImage.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

    // 入力フィールドからカード名を取得
    cardName = nameInputField.text;

    // カード情報を保存
    SaveCardInfo(imagePath, cardName);

    // パスをクリアして、次回ボタンが押されるまで再選択を防ぐ
    imagePath = null;
}

Texture2D LoadTexture(string path)
{
    byte[] fileData = File.ReadAllBytes(path);
    Texture2D texture = new Texture2D(2, 2);
    texture.LoadImage(fileData);
    return texture;
}

void SaveCardInfo(string imagePath, string cardName)
{
    string saveDataPath = Path.Combine(Application.persistentDataPath, "cardData.txt");

    // カード情報をファイルに追記して保存
    File.AppendAllText(saveDataPath, $"{cardName},{imagePath}\n");
}

}

0

1Answer

単純にStartを複数回呼び出してそうなので、onclickをみてみたらわかるんじゃないかな?

0Like

Your answer might help someone💌