Enum unity что это

Перечисления в C#: как правильно использовать enum

В C# есть много крутых инструментов, которые позволяют улучшить любой код. Один из них — enum. Давайте разберёмся, что это и как с ним работать.

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Списки перечисления (или enum) сокращают код и улучшают его читаемость. В этой статье мы создадим enum и научимся применять его эффективно.

Что такое enum в C#

Это список однотипных значений: цветов, состояний, способов выравнивания и так далее. Например, в C# существует встроенный список цветов:

То есть нам не нужно вручную вводить код цвета — вместо этого мы просто выбираем значение из заранее составленного списка.

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

В самом enum тоже не хранится код цвета. Цифра 9 на примере выше — это индекс элемента в списке. Логика изменения цвета в нашем случае примерно такая:

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Пишет о программировании, в свободное время создает игры. Мечтает открыть свою студию и выпускать ламповые RPG.

Как создать enum в C#

Создайте отдельный файл и назовите его так, чтобы понять, какой это список. Например, Direction.cs:

После объявления нового enum он используется как тип данных:

Вы можете указать и какие-то собственные значения для элементов. Например, коды ответа веб-сервера:

По умолчанию тип значения — int, но он изменяется на любой другой целочисленный тип:

Как использовать enum в C#

Самый простой пример — конструкции if и switch.

Вот результат работы такой программы:

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Также вы можете использовать enum вместе с полиморфизмом.

Таким образом вы получите код, который очень быстро читается. И теперь не нужно думать, какой метод использовать, — благодаря полиморфизму всё выглядит почти как человеческая речь: set item type — Food (указать тип предмета — Еда).

Другая хорошая практика — использовать enum в качестве возвращаемого типа для методов, в которых ошибка может произойти по разным причинам. Например, отправка данных на сервер.

Этот метод возвращает три сообщения в зависимости от ситуации:

Конечно, допустимо куда больше вариантов: от ошибки базы данных до превышения времени ожидания.

Как enum помогает улучшить читаемость

Представим, что у нас есть класс Item со следующими полями:

Все эти значения передаются объекту через конструктор, поэтому инициализация выглядит так:

Без enum со временем вы забудете, за что отвечает третий аргумент, и вам придётся каждый раз проверять реализацию класса, чтобы освежить память. Или вы добавите новые типы предметов, из-за чего таких аргументов ( isArmor, isPotion) станет ещё больше:

Избежать таких неприятных моментов как раз и помогает enum: создайте перечисление ItemType и передавайте в конструктор его.

С первого взгляда понятно, что здесь имеется в виду.

Источник

Для обнаружения столкновений на GateManager я использовал теги для каждого шлюза. Так, например:

Приведенный выше код не является точным, но должен дать представление. Было неправильно неправильно устанавливать каждый тип ворот в качестве отдельного тега (если каждый тип ворот имеет разные теги, а каждый тип материала имеет разные теги и т. Д., Я получу сотни тегов).

Поэтому я придумал альтернативу. Я установил перечисление GateType и создал 3 значения (WoodenGate, StoneGate, MetalGate). Затем я прикрепил открытое свойство GateType к классу GateManager. Это позволило мне выбрать, какое перечисление относилось к каждому сборному в окне «Инспектор» единства. Это было очень опрятно, и я был действительно счастлив.

Затем возникла проблема: я добавил четвертое перечисление в середине списка (например, GlassGate). Поскольку перечисления являются просто значениями int, 3-й элемент больше не был MetalGate, а теперь был StoneGate. Это означало, что у железобетонных сборных ворот неожиданно появился тип ворот каменных ворот. Который сломал мою игру.

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

Я предполагаю, что это должно быть общим требованием для многих игр (например, в играх вы можете использовать свою кирку на множестве различных игровых объектов для сбора различных ресурсов), так что просто удивляетесь лучшей практике?

3 ответа

Перечисления являются наиболее удобным способом сделать это. Добавьте индекс к значению enum и увеличьте его вручную.

Теперь, если вы хотите добавить еще один в середине списка, сделайте это так:

Unity должен сохранять правильные значения для ваших объектов, так как вы добавили индекс.

Тогда вы наследуете от него в своих скриптах:

Проверьте, какой это во время столкновения:

Прикрепите единственный скрипт, который описывает тип ворот, который этот объект представляет ко всем префабам объекта Gate, затем выберите enum для каждого из редактора или скрипта.

Проверьте, какой это во время столкновения:

Вы можете настроить его в соответствии с событием spawn / init. Если вы собираетесь использовать метод enum, вы можете просто определить его при появлении объекта. Это, очевидно, зависит от вашей игровой механики. Тем не менее, я бы, вероятно, передал это монобовету специально для материального поведения, которое вы хотите. Таким образом, если вы хотите изменить поведение деревянных арок, вам просто нужно обновить один скрипт, и он самодостаточен. это поможет по мере увеличения вашей кодовой базы и улучшит время компиляции и загрузки, если вы будете использовать функции 2017.3, которые позволяют вам определять, какие файлы входят в какие сборки

Источник

Упрощаем рисование Enum Flags в Unity

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

В этой публикации я постараюсь вкратце рассказать о типе перечисления в C#, применении его в качестве флагов, а так же о том, как можно упростить их рисование в инспекторе Unity.

Что такое Enum?

Перечисления являются значимым типом в языке C#, состоящим из набора констант. Для его объявления используется ключевое слово enum. Каждый перечислитель имеет целочисленное значение. Первый по умолчанию 0, а последующие увеличиваются на 1.

Для переопределения значений можно воспользоваться инициализаторами.

Каждый тип перечисления имеет базовый тип, в роли которого может выступать любой целочисленный тип кроме char (по умолчанию используется int). Его также можно указать явно.

Флаги

Порой возникает необходимость наделить сущность рядом свойств. Можно объявить несколько полей или завести список, но иногда достаточно одного перечисления. Для использования перечисления в качестве флагов следует добавить специальный атрибут System.FlagsAttribute. При этом требуется явная инициализация значений, каждое из которых возводится в степень.

С помощью побитовой операции OR можно объединять элементы перечисления, а используя метод HasFlag(Enum) проверять наличие битовых полей в экземпляре.

С помощью побитовой операции AND можно также осуществлять проверки.

Перечисления в Unity

Для примера возьмём нижеприведённый код.

Встроенные средства Unity позволяют отображать перечисления в виде выпадающего списка.

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

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

Далее нужно реализовать свой PropertyDrawer. Если сериализуемое свойство имеет атрибут Flags, то для рисования будем использовать метод EditorGUI.MaskField, а в противном случае стандартный метод EditorGUI.PropertyField. Также следует учесть, что свойство может являться элементом массива. Приведённый ниже код следует поместить в папку с именем Editor.

Теперь поле корректно отображается в инспекторе для любого Enum типа.

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

В дополнение к определённым значениям перечисления редактор добавляет ещё два:

Источник

Education & Technology Blog

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Have you ever been working on your game in Unity and wondered how you could create a custom type for a system you were working on? Well, wonder no more! The C# language (and many other languages) have a solution to this problem by using something called an enum. In this blog, we’ll review what enums are and how you can use them. Then we will use enums to dictate some UI input.

What is an Enum?

Simply put, an enum is a custom type that you can create in your scripts. The example Microsoft uses on their documentation is creating an enum for days of the week. So, you create an enum called Days, and there are seven different Days you could use in your program: Sat, Sun, Mon, Tue, Wed, Thur, Fri. You could call on any of these by saying Days.Sat or Days.Mon.

each enum type (E.G: Sat, Sun, Mon) has its own underlying type, which is int by default. So, technically, Sat, Sun, and Mon are values 0, 1, and 2. It is possible to specify the underlying type of the enum, but I won’t be getting into that. Refer to the Microsoft documentation if you’re interested in that.

Why Use an Enum?

This seems unnecessary, why would I use enums? I admit that enums seem rather specific in their use. It can be difficult to see where an enum could be useful in your game. It wasn’t until recently that I actually found myself using an enum to overcome a problem in Unity. For me, the decision to use an enum was made when I realized that the system I wanted to create would have required me to create 5 separate bools to keep track of the state of my script. Obviously, with 5 bools dictating the state of something in my script, my if-statement spaghetti would have been intense, which would likely lead to some odd bugs and behavior that would take more time to troubleshoot. I realized that I could remedy this situation by using an enum to keep track of the states in my script.

Let’s Make Something Using Enums!

The above-mentioned system I was trying to create was actually quite simple; a UI with four items the user could select using the arrow keys on the keyboard. Each item is either up, down, left, or right on the UI Panel. I wanted it so if the user pressed up, the up item was selected. This selection would be indicated with a fading icon in the up direction.

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

For example, in the above screenshot, if the user presses the up arrow, the sword icon would fade in and out to indicate it is selected. At this point, if the user presses up again, a command associated with the up button would execute. Otherwise, if the user pressed any of the other arrow keys, then those icons would highlight and be considered the active selection.

Let’s recreate this system right now so you can get an understanding of using enums. First of all, create a new unity project. Let’s make it 2D for simplicity. I’m going to assume you have a general knowledge of Unity so I will not explain certain steps.

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

You’ll need to do this for each of the buttons. By the end of it you should have an Up, Down, Left, and Right input. Each one should have a positive button that corresponds to its name. This will make our input detect arrow key input on our keyboard.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class SkillInput : MonoBehaviour
<

[SerializeField]
float fadeRate = 4f; //Used to adjust image fade speed

enum Selection < None, Up, Down, Left, Right >; //Will be used to keep track of what’s selected
Selection currentSel; // Create a Selection object that will be used throughout script

Image imgUp, imgDown, imgLeft, imgRight; //These variables will be used for fading the buttons when selected
Button buttonUp, buttonDown, buttonLeft, buttonRight; //Will be used to invoke Button functions

void Start()
<
currentSel = Selection.None; //assign currentSel to None.

//Grab the Image components of all our buttons
imgUp = transform.FindChild(«Up»).GetComponent ();
imgDown = transform.FindChild(«Down»).GetComponent ();
imgLeft = transform.FindChild(«Left»).GetComponent ();
imgRight = transform.FindChild(«Right»).GetComponent ();

//Grab the Button components of all our buttons
buttonUp = transform.FindChild(«Up»).GetComponent ();
buttonDown = transform.FindChild(«Down»).GetComponent ();
buttonLeft = transform.FindChild(«Left»).GetComponent ();
buttonRight = transform.FindChild(«Right»).GetComponent ();
>

void Update()
<
//Standard input calls.
if (Input.GetButtonDown(«Up»))
<
if (currentSel == Selection.Up)
<
//Executes if we already have up selected and user presses up again
buttonUp.onClick.Invoke(); //Call up button’s OnClick() function
currentSel = Selection.None; //set currentSel back to None
>
else
<
currentSel = Selection.Up; // changes currentSel to Up.
StartCoroutine(FadeIcon(imgUp, currentSel)); //Begins fading the icon
>
>
//The same code pattern from above is repeated for the rest of the inputs
else if (Input.GetButtonDown(«Down»))
<
if (currentSel == Selection.Down)
<
buttonDown.onClick.Invoke();
currentSel = Selection.None;
>
else
<
currentSel = Selection.Down;
StartCoroutine(FadeIcon(imgDown, currentSel));
>
>
else if (Input.GetButtonDown(«Left»))
<
if (currentSel == Selection.Left)
<
buttonLeft.onClick.Invoke();
currentSel = Selection.None;
>
else
<
currentSel = Selection.Left;
StartCoroutine(FadeIcon(imgLeft, currentSel));
>
>
else if (Input.GetButtonDown(«Right»))
<
if (currentSel == Selection.Right)
<
buttonRight.onClick.Invoke();
currentSel = Selection.None;
>
else
<
currentSel = Selection.Right;
StartCoroutine(FadeIcon(imgRight, currentSel));
>
>
>

IEnumerator FadeIcon(Image img, Selection sel)
<
//basic Fade Coroutine. For more Information:
//https://blog.studica.com/create-a-fading-splash-screen-using-coroutines-in-unity-3d
float alpha = 1f;

using UnityEngine;
using System.Collections;

public class TestMessage : MonoBehaviour <

public void Testing()
<
Debug.Log(«Test Succeeded!»);
>
>

using UnityEngine;
using System.Collections;

public class TestMessage : MonoBehaviour <

public void Testing()
<
Debug.Log(«Test Succeeded!»);
>
>

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

This ensures that the button will call our “Testing” function when it’s invoked.

Conclusion

Hopefully, this exercise demonstrates how enums can be useful. Imagine what this system would look like if you had used bools instead of an enum to try and dictate what object is selected at any given time. It would get ugly really quick. The if statements would become very long and confusing. You would be setting bools to true and false all over the place. By doing it this way, you’re able to keep track of your selection in a very clear and concise way. The naming of the enum is straightforward and you are controlling your selection with a single variable.

In the end, it’s important to understand how enums fit into your programming toolbox. While you won’t use them extensively, they can be incredibly useful in solving certain problems, such as the one covered in this blog. So, while you may not use enums in every script you write, I can guarantee you will come across a few problems that will best be handled by using them.

Blogger: Mark Philipp, Application Engineer at Studica

Источник

Enum, Flags and bitwise operators

If you’re a game developer chances are you’re familiar with the need to describe different variations of an attribute. Whether it’s the type of an attack (melee, ice, fire, poison, …) or the state of an enemy AI (idle, alerted, chasing, attacking, resting, …) you can’t escape this. The most naive way of implementing this is simply by using constants:

The enum construct

Luckily, C# has a construct called enum (for enumeration) which has been specifically designed for these situations:

The definition of an enum creates a type which can support only a limited range or values. These values are given symbolic labels for clarity and are also returned as string when needed:

Internally, every label has an integer value. Enums starts from zero and every new label is assigned the next integer number. None is zero, Melee is one, Fire is two and so on. You can change that by explicitly changing the value of a label:

Casting an enum to int will return its integer value. To be fair, enums are actual integers.

What makes enums even so interesting is the fact that they are automatically integrated in the Unity inspector. If a public field is an enum, it will conveniently appear like a dropdown menu:

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Enums and Flags

In the example above, attackType both holds Melee and Fire values. We’ll see later how it is possible to retrieve these values. But first we need to understand how this is actually working. Enums are store as integers; when you have consecutive numbers, their bit representations look like this:

If we want to use [Flags] at its best, we should use only powers of two for the values of our labels. As you can see below, this means that every non-zero label has exactly one 1 in its binary representation, and that they are all in different positions:

Bitwise operators

A bit mask is, essentially, an integer value in which several binary property (yes/no) are independently stored in its bit. In order to pack and unpack them we need some special operators. C# calls them bitwise operator, because they work on a bit to bit basis, ignoring carries unlikely addition and subtraction operators.

Bitwise OR

Setting a property is possible using the bitwise OR :

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

If you want the mixed type to appear, you’ll have to define it manually in the enum:

Enum unity что это. Смотреть фото Enum unity что это. Смотреть картинку Enum unity что это. Картинка про Enum unity что это. Фото Enum unity что это

Bitwise AND

The complementary operator to the bitwise OR is the bitwise AND. It works in the exact same way, with the exception that when applied with two integers it keeps only the bits which are set in both of them. While bitwise OR is used to set bits, bitwise AND is typically used to unpack property previously stores in an integer.

Bitwise NOT

There is another useful bitwise operator, which is the bitwise NOT. What it does is simply inverting all the bits of an integer. This can be useful, for instance, to unset a bit. Let’s say we want our attack to stop being firey and become icy instead:

Bitwise XOR

After OR, AND and NOT, we cannot not mention the bitwise XOR. As the name suggest, it is used to xor bits in the same position of an integer variable. The xor (or exclusive or) of two binary values is true only if one or the other is true, but not both. This has a very important meaning for bit masks, since it allows to toggle a value.

Bitwise shifts

The last two operators to work with bit masks are the bitwise shifts. Taken a number, they literally shift its bits right (>>) or left ( Alan Zucconi

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *