개발 관련/SW, App 관련

Unity에서 File Open Dialog 사용하기

by 소서리스25 2023. 4. 18.
반응형

Unity에서 File Open Dialog 사용하기

 

Unity로 주로 개발한 사항들은 대부분 콘텐츠 구동용이나 앱 위주로 진행을 했었는데,

드물게 윈도우 어플리케이션을 개발할 일이 있었다. AR 등록을 위한 매니저 프로그램을 진행했다가

중단했었는데, 여기에 사용자의 커스텀 QR코드나  바코드를 등록하기 위한 어플리케이션이었다.

여기에서 사용한 File Open Dialog를 유니티에 적용하였다.

 

따라서 이번에는 File Open Dialog를 유니티에서 사용방법을 알아본다.

샘플 예제는 지난번 Video Play를 응용하여 mp4 영상 파일을 불러와서 플레이하는 것으로 간략하게 진행해 본다.

 

우선 File Open Dialog를 사용하기위해서는 2개의 스크립트가 필요하다.

먼저 Dialog 호출을 위한 스크립트는 다음과 같다. 기본적인 파일타입으로

mp4 확장자를 가진 것만 로딩 하도록 하였다.

아울러 선택된 파일의 경로 정보를 Video Play의 플레이어콘트롤 클래스로 보내기 위해

간편하게 FindObjectType를 통해 전달하도록 사용하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using UnityEngine;
using System.Runtime.InteropServices;
 
public class OpenFile : MonoBehaviour
{
 
    public void OpenFileDialog()
    {
        OpenFileName ofn = new OpenFileName();
 
        ofn.structSize = Marshal.SizeOf(ofn);
 
        ofn.filter = "MP4\0*.mp4\0\0";  // "All Files\0*.*\0\0";
 
        ofn.file = new string(new char[256]);
        ofn.maxFile = ofn.file.Length;
 
        ofn.fileTitle = new string(new char[64]);
        ofn.maxFileTitle = ofn.fileTitle.Length;
 
        ofn.iniialDir = @"./";
        ofn.title = "Open File - MP4";
        ofn.defExt = "mp4";
 
        ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008// OFN_exploer | OFN_filemustexist | OFN_pathmustexist | OFN_allowmultiselect | OFN_nochangedir
 
        if (DllTest.GetOpenFileName(ofn))
        {
            print("Selected file with full path : " + ofn.file);
 
            FindObjectOfType<PlayControllerFile>().FileLoad(ofn.file);
        }
    }
}
 
cs

 

그다음은 Dialog에서 파일을 호출을 위한 스크립트로 다음과 같다.

이 스크립트에서는 Windows 운영 체제의 Comdlg32.DLL을 이용하는 일반적인 대화 상자 관련

기능을 수행한다. 이를 활용한 스크립트이다.(출처 : 인터넷)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Runtime.InteropServices;
 
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr intance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String iniialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
 
}
 
public class DllTest
{
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
 
    public static bool GetOpenFileName1([In, Out] OpenFileName ofn)
    {
        return GetOpenFileName(ofn);
    }
}
cs

 

스크립트 코드가 준비되었다면 먼저 Canvas UI에 열기 버튼을 만들어 둔다.

 

그리고 지난번의 Video Play 코드에서 필요한 몇가지를 추가하면 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using UnityEngine;
using UnityEngine.Video;
 
public class PlayControllerFile : MonoBehaviour
{
    public VideoPlayer _video;
 
    private void Start()
    {
        //_video.url = "./Video/video_1.mp4";
    }
 
    public void Controller(string mode)
    {
        switch (mode)
        {
            case "play":
                if (_video.isPrepared)
                {
                    _video.Play();
                    _video.playbackSpeed = 1;
                }                
                break;
 
            case "pause":
                if (_video.isPrepared)
                {
                    _video.playbackSpeed = 0;
                }
                break;
 
            case "stop":
                if (_video.isPrepared)
                {
                    _video.Stop();
                    _video.frame = 0;
                }
                    
                break;
 
            case "open":
                FindObjectOfType<OpenFile>().OpenFileDialog();
                break;
        }
    }
 
    public void FileLoad(string _path)
    {
        _video.url = "file://" + _path;
        _video.Prepare();
    }
}
 
cs

 

수정한 사항은 비디오 파일이 준비되었는지 여부를 확인하기 위한 _video.isPrepared 구문, 

추가한 것은 switch문의 "open" , 그리고 File Dialog에서 받아온 선택된 동영상 파일과 경로이다.

그리고 불러온 비디오 파일이 준비상태가 되어야 하므로 _video.Prepare()로 설정한다.

 

스크립트를 적용한 객체에 대한 인스펙터는 다음과 같다.

URL은 불러올 것이므로 비워둔다.

 

유니티의 인스펙터 설정화면
유니티의 인스펙터 설정화면

 

그러면 정상 작동하는지 확인해 보자.

현재는 동영상만 활용했지만 텍스트 문서나 이미지 등에서 어플리케이션 개발시 매우 잘 활용할 수 있을 것 같다.

 

File Open Dialog 유니티

 

반응형

댓글