简体   繁体   中英

How to open a child of asset in inspector from code (Unity)

Eg I have Prefab MyPrefab, it has two childs (child_1, child_2).

AssetDatabase.OpenAsset(child_1); opens MyPrefab in inspector instead of child_1.

I'm gonna assume that you have a prefab and inside that prefab you have an another prefab that you wish to open using C#.

You can do that by using the PrefabUtility.GetCorrespondingObjectFromSource method on the child prefab that you wish to open and then calling AssetDatabase.OpenAsset method on the result that is returned.

Example

using UnityEditor;
using UnityEngine;

public class TestScript : MonoBehaviour
{
    [SerializeField]
    private GameObject prefab = null;

    [SerializeField]
    private string childPrefabName = string.Empty;

    private void Run()
    {
        var child = prefab.transform.Find(childPrefabName);
        var childPrefab = PrefabUtility.GetCorrespondingObjectFromSource(child);

        AssetDatabase.OpenAsset(childPrefab);

    }

    [CustomEditor(typeof(TestScript))]
    public class TestScriptEditor: Editor
    {
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            if (GUILayout.Button("Run"))
            {
                var script = target as TestScript;
                script.Run();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM