Unity

사용자의 배경 화면을 유니티 화면에 띄우기 1

psb08 2025. 2. 17. 16:57
728x90
반응형

사용자의 배경 화면을 유니티 배경에 띄워보고 싶어 도전 했습니다.

 

먼저 영상을 보자면 제 배경화면 (테스트용)이 유니티 화면에 뜨며, 사진의 경로와 이미지 로드 성공! 이라는 메세지가 뜹니다. 

 

저희는 WinAPI를 사용하여 Sprite Renderer에 사진을 넣는 방식으로 만들 겁니다.

먼저 빈 오브젝트를 만든 뒤, 사진을 넣을 SpriteRenderer를 넣습니다.

 

WallpaperManager.cs

using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class WallpaperManager : MonoBehaviour
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern int SystemParametersInfo(int uAction, int uParam, System.Text.StringBuilder lpvParam, int fuWinIni);

    private const int SPI_GETDESKWALLPAPER = 0x0073;

    public static string GetWallpaperPath()
    {
        System.Text.StringBuilder path = new System.Text.StringBuilder(200);
        SystemParametersInfo(SPI_GETDESKWALLPAPER, path.Capacity, path, 0);
        return path.ToString();
    }
}

WallpaperManager를 만듭니다.

 

한 줄 한 줄 설명하자면,


using 부분

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

using 구문은 필요한 네임스페이스를 포함합니다.

System.Collections과 System.Collections.Generic은 컬렉션 관련 클래스,

System.Runtime.InteropServices는 네이티브 API 호출을 위한 클래스,

UnityEngine은 Unity 관련 클래스들을 포함합니다.

 

Attribute 부분

[DllImport("user32.dll", CharSet = CharSet.Auto)]

DllImport 특성(attribute)을 사용해 user32.dll이라는 외부 라이브러리에서 함수를 가져옵니다.

이 라이브러리는 Windows의 사용자 인터페이스와 관련된 함수들을 포함하고 있습니다.

CharSet.Auto는 문자열 처리를 자동으로 처리하도록 지정합니다.

 

함수 부분

private static extern int SystemParametersInfo(int uAction, int uParam, System.Text.StringBuilder lpvParam, int fuWinIni);

SystemParametersInfo는 Windows API 함수로, 시스템 설정을 가져오거나 변경하는 데 사용됩니다.

이 함수는 네이티브 코드에서 호출되므로 extern 키워드를 사용합니다.

 

uAction, uParam, lpvParam, fuWinIni는 함수에 필요한 매개변수들입니다.

   uAction은 어떤 작업을 수행할지 지정합니다.

   uParam은 작업에 필요한 추가 파라미터입니다.

   lpvParam은 결과를 받을 StringBuilder 객체입니다.

   fuWinIni는 윈도우 설정에 적용할지 여부를 지정하는 값입니다.

 

private const int SPI_GETDESKWALLPAPER = 0x0073;

SPI_GETDESKWALLPAPER는 SystemParametersInfo 함수에서 사용할 상수 값입니다.

0x0073은 바탕화면 배경 이미지 경로를 가져오는 작업을 나타냅니다.

 
public static string GetWallpaperPath()
{
    System.Text.StringBuilder path = new System.Text.StringBuilder(200);
    SystemParametersInfo(SPI_GETDESKWALLPAPER, path.Capacity, path, 0);
    return path.ToString();
}

GetWallpaperPath는 배경화면 경로를 반환하는 메서드입니다.

static으로 정의되어 있으므로 클래스 이름을 통해 호출할 수 있습니다.

 

첫번 째 줄

StringBuilder는 변경 가능한 문자열을 처리하는 클래스입니다.

여기서는 200 크기의 버퍼를 생성하여 배경화면 경로를 저장할 준비를 합니다.

 

두번 째 줄

SystemParametersInfo를 호출하여 배경화면 경로를 path 객체에 저장합니다.

path.Capacity는 최대 버퍼 크기를, path는 결과를 받을 객체를, 0은 윈도우 설정 변경 여부를 의미합니다.

 

마지막 줄

StringBuilder에 저장된 경로를 문자열로 반환합니다.


코드 하나만 설명 했는데 양이 꽤 되어서 조금 더 다듬은 후에 내일 글을 작성하겠습니다.

 

'Unity' 카테고리의 다른 글

사운드 감지하기 1  (0) 2025.02.19
사용자의 배경 화면을 유니티 화면 띄우기 2  (0) 2025.02.18
그랩팩 개발 일지 10  (0) 2025.02.16
그랩팩 개발 일지 9  (0) 2025.02.15
그랩팩 개발 일지 8  (0) 2025.02.14