Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

unity3d - How to access Dictionary from other Class's function in C#_ Unity

I am new to C# and I don't have much idea how to proceed to get metadata that is in a script that is attached to the GameObjects. How can I see this information in branch to display it in the Inspector?

namespace Speckle.ConnectorUnity
{
    /// <summary>
    /// This class gets attached to GOs and is used to store Speckle's metadata when sending / receiving
    /// </summary>
    public class SpeckleData : MonoBehaviour
    {
        public Dictionary<string, object> Data { get; set; } 
    }
}

Your answer would be of great help, thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to check the documentation to check what are the types that you can see in the inspector.

As you will be able to read, the serialization is done with an internal Unity serialization system; not with .NET's serialization functionality. So not all the c# classes are able to be shown in the editor as serialized fields. On the other hand your dictionary is a property. Check that you cannot serialize properties also in the docs.

My recomendation is that if you want to do that, make your template classes to be shown in the editor as serializable, and with the fields that you know can be shown in the editor spreaded in your class as variables of it, like this:

    [Serializable]
    class MyInspectorCoolClass {
        int myInt;
        string myString;
    }

    class MyMonoBehaviour: MonoBehaviour {
        public MyInspectorCoolClass myFields; //your fields will be displayed in the inspector
    }

So, for your specific case you would need to know the object concrete type to be serialized. In case you need to show in the inspector a set of key, value objects as I think you intend with your dictionary, I recomend that you make a List of your inspector typeholder class, following my example, like this:

class MyMonoBehaviour: MonoBehaviour {
    public List<MyInspectorCoolClass> myFields; 
}

Or a private serialize field, to be shown in the editor for a reference to be attached, but keep it private regarding the access to the variable in the code.

class MyMonoBehaviour: MonoBehaviour {
    [SerializeField]
    private MyInspectorCoolClass myFields; //your fields will be displayed in the inspector
}

In case you might be tempted, c# Tuples cannot be shown as serialized fields in the inspector neither.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...