Home > unity > How to edit key-value pairs (like a Dictionary) in Unity's inspector?

How to edit key-value pairs (like a Dictionary) in Unity's inspector?

May 2Hits:3
Advertisement

I have a spell system I am creating, the principle is as follows:

  • Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector.
  • I have a Spell enum listing all possible spells in the code, which is used in the game logic
  • When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations
  • Each actor (be it players or enemies) needs to have a list of possible animations for the spells

The problems with how I am trying to implement are:

  • For listing each actor's animations I could use a Dictionary<Spell, Animation>, but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type.
  • I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary

I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations

Answers

One quick way to get key-value pairs in Unity's inspector is to define a serializable entry class, and then use an array or List<> of them. eg...

public class SpellAnimationMap : ScriptableObject
{
   [System.Serializable]
   public class SpellAnimationEntry
   {
       public Spell spell;
       public AnimationClip animation;
   }

   public SpellAnimationEntry[] spellAnimations;
}

Automatically, this will give you a resizeable list in the inspector where you can enter the key and value, without needing to write a custom inspector.

The result looks like this:

How to edit key-value pairs (like a Dictionary) in Unity's inspector?

(One trick: if the serialized entry class contains a "Name" field, that string will be displayed instead of the bland "Element 0" headings. Useful if you have more complex data you want to be able to navigate efficiently.)

Making this a ScriptableObject allows you to treat it as an Asset shared between entity types/instances that need the same animation set, avoiding overhead of duplicating the list for each. (Other classes tend to be serialized per-instance in Unity). To go this route, you'll need to add a small editor script to let you create instances of these in your Assets folder.

You can optionally make the array private and serialized so that it still shows up in the inspector, but add a public Dictionary (or private dictionary with a public GetAnimation(Spell spell) method) for clients to consume for more efficient lookups. In its OnEnable() method, the SpellAnimationMap can iterate through its inspector-populated array to build this dictionary once, again sharing the benefit between all client instances. (Note that OnEnable() is also called in the editor when the asset is first created, so be sure to check that your array is non-null before you try to read it)

Finally, you can add as much into this entry datatype as you need. It could include the prefab too, for instance, or any number of other bits of data you want to link to the spell key.

It's also possible to write custom inspectors to populate Dictionary<,> fields directly, but the impression that I get is that it's fussy to get working smoothly.

Related Articles

  • How to edit key-value pairs (like a Dictionary) in Unity's inspector?

    How to edit key-value pairs (like a Dictionary) in Unity's inspector?May 2

    I have a spell system I am creating, the principle is as follows: Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector. I have a Spell enum listing all possible

  • deserialize XML to Dictionary key value pair like JsonFebruary 10

    How can we deserialize a xml API response and save it as key value pair in a Dictionary in c#. I am successfully able to that for Json response.please explain with a simple example.

  • How to write a class that accepts an optional key-value pair?December 15

    a user-defined class: \ProvidesClass{preview}[2012/12/15 v 0.01 class for creating a tight PSTricks diagram] \DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}} \ProcessOptions\relax \LoadClass[]{article} \RequirePackage{pstricks} \RequireP

  • Extract key-value pairs from a stringJune 24

    I want to extract key value pairs from a string. I need this to define a new glossary style and want to pass some additional information through a existing parameter. \newglossarystyle{meinglossar}{% \renewenvironment{theglossary}{\begin{description}

  • Create a hash from an array of arrays of key|value pairsSeptember 12

    Starting from an array of sub-arrays, each sub-array is a 2 elements key|value pair. Example input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]] Convert this into a hash that has distinct keys fro

  • Optimal way to store 18 billion key, value pairs June 5

    I have around 200 million new objects coming in, and a 90 day retention policy, so that leaves me with 18 billion records to be stored in the form of key-value pairs. Key and value both will be a string. It is basically a mapping between a unique ide

  • The best way to store static key value pair listApril 28

    I wish to store a static key value pair list, around 200 pairs. A few ways i can think of are the - variable_get set - custom table - cache - define constant in code - hardcoded in code The list will be referenced on every node. I am using views as w

  • Changing the key/value pair of a field list in Drupal 7 once content has been added to the site

    Changing the key/value pair of a field list in Drupal 7 once content has been added to the siteMarch 31

    I have a field list on my content type that I need to edit. Specifically I just need to change one of the key/value pairs. Unfortunately there's already content in the site so I can't just change it in the admin interface (it gives me an error that t

  • Is this a good solution for deactivating key value pairs?October 23

    A (relatively) simple CRUD application on which I work has a lookup table which holds key-value pairs, some of which have child key-value pairs. These are used mainly in drop-down lists on the application front end. Currently there is a RowStatus fie

  • Pandas: Reconstruct dataframe from strings of key:value pairsJanuary 28

    Suppose I have following dataset: 0 0 foo:1 bar:2 baz:3 1 bar:4 baz:5 2 foo:6 So each line is essentially a dict serialized into string, where key:value pairs are separated by space. There are hundreds of key:value pairs in each row, while number of

  • how can I add key value pairs to an array?July 16

    How can I add key value pairs to an array? This won't work: public function getCategorieenAsArray(){ $catList = array(); $query = "SELECT DISTINCT datasource_id, title FROM table"; if ($rs=C_DB::fetchRecordset($query)) { while ($row=C_DB::fetchR

  • How can I add a key/value pair to a JavaScript object?July 22

    Here is my object literal: var obj = {key1: value1, key2: value2}; How can I add {key3: value3} to the object? --------------Solutions------------- There are two ways to add new properties to an object: var obj = { key1: value1, key2: value2 }; Using

  • Removing ssh key value pairJuly 26

    I generated new ssh key value pair for logging onto my server. I now want to disable usage of the first key pair cause old users have it and it's a security risk. How do I do that. --------------Solutions------------- There is a file at /home/<user>

  • How do I create an Excel Macro to output key/value pairs to file?October 22

    I have two columns as key/value pairs and want to export them to a file in the structure key=value (to create a properties file). I tried this script: Sub Properties() Dim FileName As String, i As Integer, str As String FileName = "C:\propstest.txt&q

  • openldap 2.4.11 - bdb_dn2id: get failed: DB_NOTFOUND: No matching key/data pair found (-30989)February 12

    I am struggling quite a while now, googled a lot and I have not yet been able to figure this - hopefully - simple problem out. I am a beginner in ldap so I might be missing something very obvious ... I have a pretty simple slapd.conf: include /privat

  • Find page IDs with specific meta tag key value pairsJune 27

    Is there a way to find the ids of the pages who contain meta tags/custom fields with a certain key-value pair? Say, for instance, that I wanted to find all of the pages who had a meta-tag/custom-field key of "weather" with a value of "raini

  • How to create dictionary and add key value pairs dynamically in JavascriptAugust 25

    From post: Sending a JSON array to be received as a Dictionary<string,string> I'm trying to do this same thing as that post, the only issue is that I don't know what the keys and the values are upfront. So I need to be able to dynamically add the ke

  • What's an alternative to data tables for key/value pairs?October 1

    I have a list of 8 key/value pairs I'm displaying in a sidebar using a table element. I'm using a th and td element on each row. However, the td content is often too long and has to be truncated. I could increase the width of the sidebar but the td c

  • How to output node fields of referenced nodes as plain-text key/value pairs?October 25

    I've got a super content-type that contains at least 4 node references. The first three references aren't always the same node-type but they contain just one referece. The third reference can contain multiple references which are all of the same type

  • Font size as a key-value pair using pgfkeys does not workDecember 21

    I want to define a new environment whose contents can be typeset using a specific font family and size optionally specified as key-value pairs. For handling the key-value pairs I am using pgfkeys. Why is LaTeX not accepting passing the font size as a

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.574 s.