unity dictionary что это

Unity — выбираем, какой массив использовать

Для тех, кто сталкивался с Unity, — не секрет, что эта платформа предоставляет большое количество разнообразных массивов — аж 5 штук (для JS и того больше — 6!). Так что же выбрать и как не запутаться в этом многообразии?

Начну — с конца. Сразу же приведу данные собранные в табличку.

Нетипизированный Типизированный
Доступ по индексу,
фиксированная длина
встроенный массив
(built-in array)
Доступ по индексу,
динамический размер
ArrayList
или Javascript Array
List
Доступ по ключу Hashtable Dictionary

А теперь — давайте поговорим о каждом в отдельности…

Javascript Array

Самый простой и самый медленный вариант массива. Доступен только в JavaScript (UnityScript). Нетипизированный, с динамичным размером. Можно хранить объекты любого типа, вперемешку. Однако, это может внести и неразбериху, а также (при использовании pragma strict) придется каждый раз приводить типы.

Использование:

UnityScript C#
объявление var a: Array = new Array();
добавление a.Add(item);
доступ a[i]
удаление a.RemoveAt(i);
размер

Документация на сайте Unity: unity3d.com/support/documentation/ScriptReference/Array.html

ArrayList

.Net тип массива аналогичный предыдущему Javascript Array, однако доступный как для UnityScript, так и для C#. Обладает все теми же преимуществами и недостатками, однако набор функций — более богат, чем в предыдущем случае.

Использование:

UnityScript C#
объявление var a: Array = new ArrayList(); ArrayList a = new ArrayList();
добавление a.Add(item);
доступ a[i]
удаление a.RemoveAt(i);
размер a.Count

Документация в MSDN: msdn.microsoft.com/en-US/library/system.collections.arraylist.aspx

Built-in array

Самый быстрый вариант массива. Однако, это жесткий массив, с фиксированной длиной, не позволяющий вставлять элементы в середину и т.п. Однако, если вам нужен максимум быстродействия — то встроенные массивы — это то, что вы ищите. Кроме того, они могут быть двухмерными.

Hashtable

Нетипизированный массив с доступом не по индексу, а по ключу. Ключ, кстати, — тоже нетипизированный (точнее, он, как и значение — являются объектами типа Object).

Использование:

UnityScript C#
объявление var a: Hashtable = new Hashtable(); Hashtable a = new Hashtable();
добавление a[«key»] = item;
доступ aunity dictionary что это
удаление a.Remove(key)
размер a.Count

Документация в MSDN: msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx

Dictionary

Аналогично Hashtable, за исключением того, что и ключ, и элемент в таком массиве имеют заданный тип. Следовательно, работает это дело быстрее и не требует лишнего type cast’а.

Использование:

UnityScript C#
объявление var a: Dictionary. = new Dictionary. (); Dictionary a = new Dictionary ();
добавление a[«key»] = item;
доступ aunity dictionary что это
удаление a.Remove(key)
размер a.Count

Документация в MSDN: msdn.microsoft.com/en-us/library/xfhwa508.aspx

Заключение

Собственно, сводная табличка была в самом начале статьи.

Что можно посоветовать? Нужна скорость — используйте встроенные массивы []. И по возможности — всегда используйте типизированные массивы. Это оградит вас от лишней путаницы, приведения типов и выиграет скорость.

Читайте также:  аллапинин или пропанорм что лучше при аритмии

Источник

Как редактировать пары ключ-значение (например, словарь) в инспекторе Unity?

У меня есть система заклинаний, которую я создаю, принцип таков:

Проблемы с тем, как я пытаюсь реализовать:

Я ищу способ легко связать перечисления моих заклинаний с соответствующими префабами и анимациями.

Автоматически, это даст вам изменяемый размер списка в инспекторе, где вы можете ввести ключ и значение, без необходимости написания специального инспектора.

Результат выглядит так:

(Один прием: если в сериализованном классе записей есть поле «Имя», эта строка будет отображаться вместо полных заголовков «Элемент 0». Это полезно, если у вас есть более сложные данные, которые вы хотите эффективно перемещать.)

Это помещает ScriptableObject в меню «Создать», например:

При желании можно сделать массив частным и сериализованным, чтобы он по-прежнему отображался в инспекторе, но добавить общедоступный словарь (или частный словарь с общедоступным методом GetAnimation (Spell spell)), который клиенты будут использовать для более эффективного поиска. В своем методе OnEnable () SpellAnimationMap может перебирать свой массив, заполненный инспекторами, для создания этого словаря, снова разделяя преимущества между всеми клиентскими экземплярами. (Обратите внимание, что OnEnable () также вызывается в редакторе при первом создании ресурса, поэтому убедитесь, что ваш массив не равен NULL, прежде чем пытаться его прочитать)

Наконец, вы можете добавить столько данных в этот тип ввода, сколько вам нужно. Например, он может включать в себя также префаб или любое количество других битов данных, которые вы хотите связать с клавишей заклинания.

Источник

How to use arrays, lists, and dictionaries in Unity for 3D game development

A key ingredient in scripting 3D games with Unity is the ability to work with C# to create arrays, lists, objects and dictionaries within the Unity platform. In this tutorial, we help you to get started with creating arrays, lists, and dictionaries effectively.

There’s nothing wrong with this. We can print and assign new values to them. The problem starts when you don’t know how many student names you will be storing. The name variable suggests that it’s a changing element. There is a much cleaner way of storing lists of data.

Let’s store the same names using a C# array variable type:

Declaring an array

The array size is set during assignment. As you have learned before, all code after the variable declaration and the equal sign is an assignment. To assign empty values to all places in the array, simply write the new keyword followed by the type, an open square bracket, a number describing the size of the array, and then a closed square bracket. If you feel confused, give yourself a bit more time. Then you will fully understand why arrays are helpful. Take a look at the following examples of arrays; don’t worry about testing how they work yet:

Читайте также:  какие степени окисления характерны для кремния

As you can see, we can store different types of data as long as the elements in the array are of the same type. You are probably wondering why the last example, shown here, looks different:

In fact, we are just declaring the new array variable to store a collection of GameObject in the scene using the «car» tag. Jump into the Unity scripting documentation and search for GameObject.FindGameObjectsWithTag :

As you can see, GameObject.FindGameObjectsWithTag is a special built-in Unity function that takes a string parameter ( tag ) and returns an array of GameObjects using this tag.

Storing items in the List

Here are the basics of why a List is better and easier to use than an array:

The first thing to understand is that a List has the ability to store any type of object, just like an array. Also, like an array, we must specify which type of object we want a particular List to store. This means that if you want a List of integers of the int type then you can create a List that will store only the int type.

Let’s go back to the first array example and store the same data in a List. To use a List in C#, you need to add the following line at the beginning of your script:

Common operations with Lists

You don’t need to understand all of these at this stage. All I want you to know is that there are many out-of-the-box operations that you can use. If you want to see them all, I encourage you to dive into the C# documentation and search for the List class.

List versus arrays

Now you are probably thinking, “Okay, which one should I use?” There isn’t a general rule for this. Arrays and List can serve the same purpose. You can find a lot of additional information online to convince you to use one or the other.

Arrays are generally faster. For what we are doing at this stage, we don’t need to worry about processing speeds. Some time from now, however, you might need a bit more speed if your game slows down, so this is good to remember.

Retrieving the data from the Array or List

Declaring and storing data in the array or list is very clear to us now. The next thing to learn is how to get stored elements from an array. To get a stored element from the array, write an array variable name followed by square brackets. You must write an int value within the brackets. That value is called an index. The index is simply a position in the array. So, to get the first element stored in the array, we will write the following code:

Читайте также:  антитела к коронавирусу g 257 что означает

Let’s extend the familyMembers example:

Checking the size

To get the size as an integer value, we write the name of the variable, then a dot, and then Length of an array or Count for List :

ArrayList

We definitely know how to use lists now. We also know how to declare a new list and add, remove, and retrieve elements. Moreover, you have learned that the data stored in List must be of the same type across all elements. Let’s throw a little curveball.

ArrayList is basically List without a specified type of data. This means that we can store whatever objects we want. Storing elements of different types is also possible. ArrayList is very flexible.

Take a look at the following example to understand what ArrayList can look like:

Dictionaries

When we talk about collection data, we need to mention Dictionaries. A Dictionary is similar to a List. However, instead of accessing a certain element by index value, we use a string called key.

Here are a few key properties of Hashtable :

I want to make sure that you won’t feel confused, so I will go straight to a simple example:

Accessing values

Now take a look at the script once again and see if you can display the age, remember that the value that we are trying to access here is a number, so we should use int instead of string :

As you can see in the preceding line, we are casting to string (inside brackets). If we were to access another type of data, for example, an integer number, the syntax would look like this:

I hope that this is clear now. If it isn’t, why not search for more examples on the Unity forums?

How do I know what’s inside my Hashtable?

This determines whether the array contains the item and if so, the code will continue; otherwise, it will stop there, preventing any error.

We discussed how to use C# to create arrays, lists, dictionaries and objects in Unity. The code samples and the examples will help you implement these from the platform.

Do check out this book Learning C# by Developing Games with Unity 2017 to develop your first interactive 2D and 3D platform game.

Источник

Информ портал о технике и не только