0

因此,假设我有这个预制资产“P”,并附有此代码。

public GameObject selfReference;

[ContextMenu("GetReference")]
public void GetReference()
{
    selfReference = gameObject;
}

请注意:“参考查找”过程由 ContextMenu 触发,因此它是在 Edit Mode而非 Play Mode 下完成的;所有这些都发生在预制资产“P”本身中,而不是放置在场景中的随机实例。


所以我尝试了

selfReference = PrefabUtility.GetNearestPrefabInstanceRoot(gameObject);

但它没有工作,所以试图通过路径加载它:

string _path = AssetDatabase.GetAssetPath(gameObject);

但它只返回空白字符串。

有什么帮助吗?

4

1 回答 1

1

我只能假设-因为它对我有用;)

在此处输入图像描述

您的问题与未正确保存此更改以及未处理撤消/重做有关。

你可能应该做例如

public GameObject selfReference;

[ContextMenu(nameof(GetReference))]
public void GetReference()
{
#if UNITY_EDITOR
    if(!Application.isPlaying)
    {
        UnityEditor.Undo.RecordObject(this, "fetched self-reference");

        if (UnityEditor.PrefabUtility.IsPartOfAnyPrefab(this))
        {
            UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this);
        }
    }
#endif

    selfReference = gameObject;
}

除此之外,对于我来说,无论如何都有一个通过属性公开的字段似乎有点多余;)

于 2022-02-10T15:25:13.777 回答