Unity---资源管理中不同资源的路径获取方式

1、首先需要先了解两个知识点: Unity内置的文件路径获取方式、windows的Directory.GetFiles文件获取方式:

   1>Unity内置的文件路径获取方式,以下是官方解释:https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html

Unity---资源管理中不同资源的路径获取方式

  以下是自己对AssetDatabase类中一些方法的简单测试:

 

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor; using UnityEngine;
using UnityEditor; public class TestAssetDatabase : Editor
{
const string TestMatPath = @"Assets/Materials/";
const string TestMatName = "TestMaterial.mat"; static string MatPath = string.Format("{0}{1}", TestMatPath, TestMatName); [MenuItem("Tools/Create Asset")]
static void CreateMaterial()
{
var material = new Material(Shader.Find("Specular"));
AssetDatabase.CreateAsset(material, MatPath); //Materials文件夹 需要手动创建
} [MenuItem("Tools/Delete Asset")]
static void DeleteMaterial()
{
AssetDatabase.DeleteAsset(MatPath);
} [MenuItem("Tools/Copy Asset")]
static void CopyMaterial()
{
AssetDatabase.CopyAsset(MatPath, "Assets/NewMaterials/TestMaterial.mat"); //NewMaterials文件夹 需要手动创建
} [MenuItem("Tools/Load Asset")]
static void LoadMaterial()
{
//加载资源两种不同的写法,需要些资源后缀的
//Material mat = AssetDatabase.LoadAssetAtPath<Material>(MatPath);
Material mat = AssetDatabase.LoadAssetAtPath(MatPath, typeof(Material)) as Material;
Debug.Log(mat.color);
} //Filter可以是:Name、Lable、Type(内置的、自定义) //Type 关键字 t:
static string fliterMat = "t:Material"; //单个
static string filterPrefab = "t:Prefab";
static string fliterMatPre = "t:Material t:Prefab"; //多个
static string filterCustomDefine = "t:CustomDefine"; //自定义的类型,需要是ScriptableObject创建的资源 //Label 关键字 l:
static string filterLabel = "l:lgs"; static string filterMixed = "Cube l:lgs"; //混合过滤---名字中有Cube,Label为 lgs [MenuItem("Tools/Find Asset")]
static void FindAsset()
{
string[] guidArray = AssetDatabase.FindAssets(filterMixed);
foreach (string item in guidArray)
{
Debug.Log(AssetDatabase.GUIDToAssetPath(item)); //转换来的资源路径是带有后缀名字的
}
}
}

   2>windows的Directory.GetFiles文件获取方式,官方解释:https://docs.microsoft.com/zh-cn/dotnet/api/system.io.directory.getfiles?view=netframework-4.7.2#System_IO_Directory_GetFiles_System_String_System_String_System_IO_SearchOption_

Unity---资源管理中不同资源的路径获取方式

Unity---资源管理中不同资源的路径获取方式

  以下是官方代码示例(指定以字母开头的文件数):

 using System;
using System.IO; class Test
{
public static void Main()
{
try
{
// Only get files that begin with the letter "c."
string[] dirs = Directory.GetFiles(@"c:\", "c*");
Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
foreach (string dir in dirs)
{
Console.WriteLine(dir);
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}

在获取不同资源的时候,只需要对不同类型的资源加以不同的过滤标签,
例如:
过滤器,若以t:开头,表示用unity的方式过滤;若以f:开头,表示用windows的SearchPattern方式过滤;若以r:开头,表示用正则表达式的方式过滤
再根据过滤标签,获取不同的资源路径即可

上一篇:uva 1597 Searching the Web


下一篇:2 JavaScript输出&字面量&变量&操作符&语句&标识符和关键字&字符集&语句&数据类型与类型转换