在 Unity 中获取预制文件位置 [英] Get a prefabs file location in Unity

查看:79
本文介绍了在 Unity 中获取预制文件位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是在我的场景中预制件 GameObjectStart() 方法中,我想获得该预制件所在位置的位置一个字符串,但我不知道如何做到这一点.

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.

我如何使用它的示例:我在我的场景中放置了一个 Sword Prefab GameObjectStart() 我想获取这个 GameObject 在我的位置的文件目录项目.

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.

推荐答案

Include using UnityEditor;

注意:这仅在预制件公开时有效.

NOTE: This will only work if the prefab is to to public.

然后使用AssetDatabase.GetAssetPath获取预制件的路径.

Then use AssetDatabase.GetAssetPath to get the path of the prefab.

public GameObject prefab;
void Start(){
    string prefabPath = AssetDatabase.GetAssetPath(prefab);
    Debug.Log("Path: " + prefabPath);
}

编辑:

我对 PrefabUtility.GetPrefabTypePrefabUtility.GetPrefabObjectPrefabUtility.GetPrefabParent 做了一些实验.PrefabUtility.GetPrefabParent 解决了这个问题.您不需要使用 PrefabUtility.GetPrefabParent 将预制件设为 public.

I did some experiment with PrefabUtility.GetPrefabType, PrefabUtility.GetPrefabObject and PrefabUtility.GetPrefabParent. PrefabUtility.GetPrefabParent solved the problem. You don't need to make the prefab public with PrefabUtility.GetPrefabParent.

void Start()
{
    GameObject prefab = GameObject.Find("PrebabTest");
    Object GameObject2 = PrefabUtility.GetPrefabParent(prefab);
    string prefabPath = AssetDatabase.GetAssetPath(GameObject2);
    Debug.Log("Path: " + prefabPath);
}

这篇关于在 Unity 中获取预制文件位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆