コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】アセットのパスを Resources.Load で使用するパスに変換する方法

概要

using System.Text.RegularExpressions;

namespace Kogane
{
    public static class ResourcesPath
    {
        private static readonly Regex REGEX = new( @"^.*Resources/(.*)\..*" );

        public static string ToResourcesPath( string assetPath )
        {
            return REGEX.Replace( assetPath, "$1" );
        }
    }
}

使用例

using Kogane;
using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
        // Materials/New Material
        Debug.Log( ResourcesPath.ToResourcesPath( "Assets/@Project/Resources/Materials/New Material.mat" ) );
        
        // New Material
        Debug.Log( ResourcesPath.ToResourcesPath( "Resources/New Material.mat" ) );
        
        // DOTweenSettings
        Debug.Log( ResourcesPath.ToResourcesPath( "Assets/Plugins/Demigiant/DOTween/Resources/DOTweenSettings.asset" ) );
        
        // Assets/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll
        Debug.Log( ResourcesPath.ToResourcesPath( "Assets/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll" ) );
    }
}