在前一个项目开发中发现需要通过Hierarchy中通过选择的模型来定为到我们在Project中的位置
于是发现了这个API:GetInstanceID
Object.GetInstanceID
public int GetInstanceID();
Returns the instance id of the object.
The instance id of an object is always guaranteed to be unique.
所有的Unity文件都会默认设置一个ID,既然发现了这个ID,那么我们就可以思考是否可以通过这个ID来找到这个模型呢?
在查找Editor中的API时发现了我们寻找的API: GetAssetPath
public static string GetAssetPath(int instanceID);
public static string GetAssetPath(Object assetObject);
Parameters
instanceID The instance ID of the asset.
assetObject A reference to the asset.
Returns
string The asset path name, or null, or an empty string if the asset does not exist.
Description
Returns the path name relative to the project folder where the asset is stored.
All paths are relative to the project folder, for example: "Assets/MyTextures/hello.png".
正好在unity中提供了这样一个API,让我们通过InstanceID返回一个路径
既然我们了解到了这个,那么尝试运用这两个API编写一个小工具呢
- 通过Hierarchy中通过选择的模型来定为到我们在Project中的位置
- 并在Hierarchy中右击模型为其在特定目录创建Prefab
- 给此Prefab创建AssetBundle包名和后缀
- 文件夹结构:
OK!我们现在了解到了我们的需求,并且通过GetInstanceID和GetAssetPath这两个API可以完成我们需求的第一部分
代码如下:
//通过Selection.gameObjects.First(),获取到的名字会带有(UnityEngine)等字样,所以我们需要将这些多余的字样移除,只保留我们的模型名称
string selectItemName = Selection.gameObjects.First().ToString().Remove(4, 25);
item = GameObject.Find(selectItemName);
var itemBody = item.transform.Find("Body").GetComponent<MeshFilter>();
var meshName = itemBody.sharedMesh.GetInstanceID();
var itemFullPath = AssetDatabase.GetAssetPath(meshName);
这样一来我们第一步的需求就完成了,那么剩下的第二点由于我们已经知道了模型的所在路径,那么第二步的代码将会很简单了。
代码如下:
//获取到SZ_M052级路径
var ItemFilePath = Directory.GetParent(Directory.GetParent(itemFullPath).ToString()).ToString();
itemPrefabPath = ItemFilePath + @"\Prefab";
//生成Prefab,并命名为Item
PrefabUtility.SaveAsPrefabAsset(item, itemPrefabPath + @"\Item" + ".prefab");
Debug.Log("---Prefab Is CreatDone---");
Debug.Log("ItemPrefabPath Is:" + itemPrefabPath);
Duang~!继续我们的第三步需求。
代码:
DirectoryInfo direction = new DirectoryInfo(itemPrefabPath);
FileInfo[] files = direction.GetFiles();
for (int i = 0; i < files.Length; ++i)
{
if (!files[i].Name.Contains(".meta"))
{
string assetpath = itemPrefabPath + @"\" + files[i].Name;
string name = files[i].Name.ToLower().Substring(0, files[i].Name.IndexOf('.'));
AssetImporter importer = AssetImporter.GetAtPath(assetpath);
if (importer != null)
{
importer.assetBundleName = "musume-" + itemFileName;
importer.assetBundleVariant = "zwa";
Debug.Log("---AssetBundle Is SetDone---");
AssetDatabase.Refresh();
}
}
}
OK,至此,我们的这一需求就完成了。
由于这一文章主要讲解的是GetInstanceID与GetAssetPath这两个API,所以在涉及其他API时,并未详细讲解。
本章就在这里结束了,希望能有帮到大家的地方,也请各位大佬指点一些不足的地方。