hostObj | 支持 SerializeReference 的宿主对象。例如 MonoBehaviour 或 ScriptableObject。 |
refId | 托管引用 ID。 |
对象返回指定宿主上并通过提供的 ID 识别的 C# 对象。如果没有找到引用对象,则返回 null。
根据其托管引用 ID 检索一个对象。
当在数组或图中的确切位置未知时,可以使用此方法有效地检索特定的引用对象。
其他资源:GetManagedReferenceIdForObject, SerializeReference。
using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Serialization;
public class GetManagedReferenceExample : ScriptableObject { [Serializable] public class Item { public char m_data; }
[SerializeReference] public List<Item> m_items = new List<Item>();
private void InsertNewItem(long id, char data) { var newItem = new Item() {m_data = data}; if (ManagedReferenceUtility.SetManagedReferenceIdForObject(this, newItem, id)) m_items.Add(newItem); }
[MenuItem("Example/ManagedReferenceUtility GetManagedReference Example")] static void TestMethod() { var scriptableObject = ScriptableObject.CreateInstance<GetManagedReferenceExample>();
scriptableObject.InsertNewItem(1000, 'a'); scriptableObject.InsertNewItem(1001, 'b'); scriptableObject.InsertNewItem(1002, 'c'); scriptableObject.InsertNewItem(1003, 'd');
// Because 1002 is registered in an earlier call this will log an error and not change the state scriptableObject.InsertNewItem(1002, 'e');
// The array may get reordered over time. One way to find an specific item again would // be to look it up based on a known managed reference id var item = ManagedReferenceUtility.GetManagedReference(scriptableObject, 1002) as Item; Debug.LogFormat("Data on object 1002 is {0}", item.m_data);
var willBeNull = ManagedReferenceUtility.GetManagedReference(scriptableObject, 9999) as Item; } }