Unity Prefab API 整理(一)
最近写些工具,发现unity2017 和unity 2018 对于prefab的API是不一样的,再记录下
一、获取Prefab类型:
unity2017
PrefabType type = PrefabUtility.GetPrefabType(orginObj); 这里的PrefabType 的类型有3种: // // 摘要: // The type of a prefab object as returned by PrefabUtility.GetPrefabType. public enum PrefabType { // // 摘要: // The object is not a prefab nor an instance of a prefab. None = 0, // // 摘要: // The object is a user created prefab asset. Prefab = 1, // // 摘要: // The object is an imported 3D model asset. ModelPrefab = 2, // // 摘要: // The object is an instance of a user created prefab. PrefabInstance = 3, // // 摘要: // The object is an instance of an imported 3D model. ModelPrefabInstance = 4, // // 摘要: // The object was an instance of a prefab, but the original prefab could not be // found. MissingPrefabInstance = 5, // // 摘要: // The object is an instance of a user created prefab, but the connection is broken. DisconnectedPrefabInstance = 6, // // 摘要: // The object is an instance of an imported 3D model, but the connection is broken. DisconnectedModelPrefabInstance = 7 }
若改资源为Prefab类型,则类型为Prefab.PrefabInstance
Unity2018
PrefabAssetType type = PrefabUtility.GetPrefabAssetType(orginObj); // // 摘要: // Enum indicating the type of Prefab Asset, such as Regular, Model and Variant. public enum PrefabAssetType { // // 摘要: // The object being queried is not part of a Prefab at all. NotAPrefab = 0, // // 摘要: // The object being queried is part of a regular Prefab. Regular = 1, // // 摘要: // The object being queried is part of a Model Prefab. Model = 2, // // 摘要: // The object being queried is part of a Prefab Variant. Variant = 3, // // 摘要: // The object being queried is part of a Prefab instance, but because the asset // it missing the actual type of Prefab can’t be determined. MissingAsset = 4 }
默认PrefabType 为PrefabAssetType.Regular
二、获取场景中选中的Prefab路径
unity2017:
这里需要注意的是:直接用AssetDatabase.GetAssetPath(object) 是获取不到prefab在Project 中的路径的,需要做层转换,
1 //TODO: 为什么要这么做?是因为在Scene你有可能选择的是Prefab下面的某个节点,需要先做层转换 2 var scenePrefab = PrefabUtility.GetPrefabParent(orginObj) as GameObject; 3 //获取Prefab路径 4 string path = AssetDatabase.GetAssetPath(scenePrefab); 5 6 //当前选中Prefab里面的节点时,想要返回Prefab 根节点 7 8 GameObject scenePrefabRoot = PrefabUtility.FindPrefabRoot(orginObj);
unity2018:
这里有直接的API可以直接获取,所以相对简单些
string prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(orginObj);
这里需要注意的是,无论选择的是scene 中prefab的哪个节点,这里都可以返回该Prefab 在Project 中的路径
结论:由此可以看出来,在unity2018 中Prefab的操作起来更方便些,另外untiy2018 还提供下,Scene下预览prefab功能,其实这块也是可以用代码控制的,这部分内容将在Unity Prefab API 整理(二) 说明。。。。
浙公网安备 33010602011771号