[英]Get a prefabs file location in Unity
What I am trying to do is in my Start()
method of a prefab GameObject
in my scene is I want to get the location of where this prefab is as a string but I cannot figure out how to do this.我想要做的是在我的场景中预制GameObject
Start()
方法中,我想获取此预制件作为字符串的位置,但我不知道如何执行此操作。
Example of how I am using this: I put a Sword Prefab GameObject
in my scene and on Start()
I would like to get the file directory of where this GameObject
is in my project.我如何使用它的示例:我在我的场景中放置了一个 Sword Prefab GameObject
,在Start()
我想获取这个GameObject
对象在我的项目中所在位置的文件目录。
Include using UnityEditor;
包括using UnityEditor;
NOTE : This will only work if the prefab is to to public.注意:这仅在预制件公开时才有效。
Then use AssetDatabase.GetAssetPath
to get the path of the prefab.然后使用AssetDatabase.GetAssetPath
获取预制件的路径。
public GameObject prefab;
void Start(){
string prefabPath = AssetDatabase.GetAssetPath(prefab);
Debug.Log("Path: " + prefabPath);
}
Edit :编辑:
I did some experiment with PrefabUtility.GetPrefabType
, PrefabUtility.GetPrefabObject
and PrefabUtility.GetPrefabParent
.我用PrefabUtility.GetPrefabType
、 PrefabUtility.GetPrefabObject
和PrefabUtility.GetPrefabParent
做了一些实验。 PrefabUtility.GetPrefabParent
solved the problem. PrefabUtility.GetPrefabParent
解决了这个问题。 You don't need to make the prefab public with PrefabUtility.GetPrefabParent
.您不需要使用PrefabUtility.GetPrefabParent
公开预制PrefabUtility.GetPrefabParent
。
void Start()
{
GameObject prefab = GameObject.Find("PrebabTest");
Object GameObject2 = PrefabUtility.GetPrefabParent(prefab);
string prefabPath = AssetDatabase.GetAssetPath(GameObject2);
Debug.Log("Path: " + prefabPath);
}
Get complete path from transform从转换中获取完整路径
public static string GetGameObjectPath(Transform transform)
{
string path = transform.name;
while (transform.parent != null)
{
transform = transform.parent;
path = transform.name + "/" + path;
}
return path;
}
If you want to find prefab variant of an instance you should use如果你想找到一个实例的预制变体,你应该使用
PrefabUtility.GetCorrespondingObjectFromSource(YourPrefabInstance)
If you want to find orginal prefab of an instance you should use如果你想找到一个实例的原始预制件,你应该使用
PrefabUtility.GetCorrespondingObjectFromOriginalSource(YourPrefabInstance)
It will work only in Editor mode.它只能在编辑器模式下工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.