- String
- String
- Actions
- Unreal Engine 4 Tutorial – Output Message to Screen
- String Handling
- An overview of the string classes available in UE4 and reference guides for FName, FText, and FString.
- FName
- FText
- FString
- Printf
- Основные приёмы Blueprint-программирования, часть 2
- Print String
- Delay, Retriggerable Delay
- MultiGate
- Sequence
- DoOnce
- Switch On Int, Switch On String
- Заключение
- Для кого этот курс?
- Что ты получишь по окончанию BlueprintME!:
- Вознаграждение за любознательность 🙂
String
String
Actions
Concatenates two strings together to make a new string
Target is Kismet String Library
Converts a boolean->string, creating a new string in the form AppendTo+Prefix+InBool+Suffix
Target is Kismet String Library
Converts a color->string, creating a new string in the form AppendTo+Prefix+InColor+Suffix
Target is Kismet String Library
Converts a float->string, create a new string in the form AppendTo+Prefix+InFloat+Suffix
Target is Kismet String Library
Converts a int->string, creating a new string in the form AppendTo+Prefix+InInt+Suffix
Target is Kismet String Library
Converts an IntVector->string, creating a new string in the form AppendTo+Prefix+InIntVector+Suffix
Target is Kismet String Library
Converts a color->string, creating a new string in the form AppendTo+Prefix+InName+Suffix
Target is Kismet String Library
Converts a object->string, creating a new string in the form AppendTo+Prefix+object name+Suffix
Target is Kismet String Library
Converts a rotator->string, creating a new string in the form AppendTo+Prefix+InRot+Suffix
Target is Kismet String Library
Converts a vector->string, creating a new string in the form AppendTo+Prefix+InVector+Suffix
Target is Kismet String Library
Converts a vector2d->string, creating a new string in the form AppendTo+Prefix+InVector2d+Suffix
Target is Kismet String Library
Returns whether this string contains the specified substring.
Target is Kismet String Library
Takes an array of strings and removes any zero length entries.
Target is Kismet String Library
Test whether this string ends with given string.
Target is Kismet String Library
Returns user friendly name of enumerator
Test if the input strings are equal (A == B)
Target is Kismet String Library
Equal, Case Insensitive (string)
Test if the input strings are equal (A == B), ignoring case
Target is Kismet String Library
Finds the starting index of a substring in the a specified string
Target is Kismet String Library
Get Character Array from String
Returns an array that contains one entry for each character in SourceString
Target is Kismet String Library
Get Character as Number
Gets a single character from the string (as an integer)
Target is Kismet String Library
Returns a substring from the string starting at the specified position
Target is Kismet String Library
Returns true if the string is empty
Target is Kismet String Library
Target is Kismet String Library
Join String Array
Concatenates an array of strings into a single string.
Target is Kismet String Library
Returns the left most given number of characters
Target is Kismet String Library
Returns the left most characters from the string chopping the given number of characters from the end
Target is Kismet String Library
Target is Kismet String Library
Returns the number of characters in the string
Target is Kismet String Library
Make Literal String
Creates a literal string
Target is Kismet System Library
Searches this string for a given wild card
Target is Kismet String Library
Returns the substring from Start position for Count characters.
Target is Kismet String Library
Test if the input string are not equal (A != B)
Target is Kismet String Library
NotEqual, case insenstive (string)
Test if the input string are not equal (A != B), ignoring case differences
Target is Kismet String Library
Parse Into Array
Gets an array of strings from a source string divided up by a separator and empty strings can optionally be culled.
Target is Kismet String Library
Prints a string to the log, and optionally, to the screen If Print To Log is true, it will be visible in the Output Log window. Otherwise it will be logged only as ‘Verbose’, so it generally won’t show up.
Target is Kismet System Library
Replace all occurrences of a substring in this string
Target is Kismet String Library
Replace all occurrences of SearchText with ReplacementText in this string.
Target is Kismet String Library
Returns a copy of this string, with the characters in reverse order
Target is Kismet String Library
Returns the string to the right of the specified location, counting back from the right (end of the word).
Target is Kismet String Library
Returns the string to the right of the specified location, counting forward from the left (from the beginning of the word).
Target is Kismet String Library
Target is Kismet String Library
If bPickA is true, A is returned, otherwise B is
Target is Kismet Math Library
Splits this string at given string position case sensitive.
Target is Kismet String Library
Test whether this string starts with given string.
Target is Kismet String Library
String to Color
Convert String Back To Color. IsValid indicates whether or not the string could be successfully converted.
Target is Kismet String Library
String To Float
Converts a string to a float value
Target is Kismet String Library
Converts a string to a int value
Target is Kismet String Library
Converts a string to a name value
Target is Kismet String Library
String to Rotator
Convert String Back To Rotator. IsValid indicates whether or not the string could be successfully converted.
Target is Kismet String Library
String to Vector
Convert String Back To Vector. IsValid indicates whether or not the string could be successfully converted.
Target is Kismet String Library
String to Vector2D
Convert String Back To Vector2D. IsValid indicates whether or not the string could be successfully converted.
Target is Kismet String Library
Time Seconds to String
Convert a number of seconds into minutes:seconds.milliseconds format string (including leading zeroes)
Target is Kismet String Library
Returns a string converted to Lower case
Target is Kismet String Library
Returns a string converted to Upper case
Target is Kismet String Library
Converts a boolean value to a string, either ‘true’ or ‘false’
Target is Kismet String Library
Converts a byte value to a string
Target is Kismet String Library
Convert a timecode structure into a string
Target is Drop Timecode to String Conversion
Converts a float value to a string
Target is Kismet String Library
Converts an integer value to a string
Target is Kismet String Library
Converts an IntPoint value to a string, in the form ‘X= Y=’
Target is Kismet String Library
Converts an IntVector value to a string, in the form ‘X= Y= Z=’
Target is Kismet String Library
ToString (linear color)
Converts a linear color value to a string, in the form ‘(R=,G=,B=,A=)’
Target is Kismet String Library
Converts a name value to a string
Target is Kismet String Library
Converts a name value to a string
Target is Kismet String Library
Converts a UObject value to a string by calling the object’s GetName method
Target is Kismet String Library
Converts a rotator value to a string, in the form ‘P= Y= R=’
Target is Kismet String Library
Converts localizable text to the string
Target is Kismet Text Library
Converts a transform value to a string, in the form ‘Translation: X= Y= Z= Rotation: P= Y= R= Scale: X= Y= Z=’
Target is Kismet String Library
Converts a vector value to a string, in the form ‘X= Y= Z=’
Target is Kismet String Library
Converts a vector2d value to a string, in the form ‘X= Y=’
Target is Kismet String Library
Removes whitespace characters from the front of this string.
Источник
Unreal Engine 4 Tutorial – Output Message to Screen
Unreal Engine 4 Tutorial – Output Message to Screen
Okay, so this simple method of printing a message to the screen while playing a game, is good to use for small stuff. For example, if the player picks up a power-up of some sort, you might want to output a message on the game screen that tells the player it has now indeed picked up and activated that specific power up. And if the power is temporary, you again might want the message to be displayed when it’s turned off.
In the example I’ll use now, I’ll simply create a message that tells the player he has entered a “Safe Zone”, and then again that he has exited the Safe Zone.
1)
Thus, the first I do is create a ground mesh, and then a simple plane on top of it, which will function as the Safe Zone. Like this:
2)
Next step is to create a basic Box Trigger, and make sure the trigger’s volume covers the entirety of the Safe Zone-field (you could also simply make the plane into a trigger volume, but I prefer not to):
3)
Now, we’ll make sure the on screen message will be printed both when the player enters and exits the Safe Zone. Thus, with the trigger selected, enter Blueprints,
right click –> AddEventForTriggerBox –> Collision –> Add OnActorBeginOverlap
and set up the next one as well:
right click –> AddEventForTriggerBox –> Collision –> Add OnActorEndOverlap
It should now look like this:
(adsbygoogle = window.adsbygoogle || []).push(<>);
4)
For the next part, we’ll do the same on both of these.
Right click in the Blueprints screen –> In the search box type in “print” and choose Print String
Do this twice and connect both to each trigger overlap. In the BeginOverlap, write something like “You have entered the Safe Zone!”
In the EndOverlap, write: “You have left the Safe Zone!”
And if you want, choose text colors, and compile Full Report. It should now look like this:
5)
Play your game and witness the magic of your message being printed to the top left corner of the screen when the player enters and exits the Safe Zone:
6)
That’s it, you’re done. Simple as nothing. Also, I created a video tutorial dealing with this, in case you’d like to watch. However, in the video I’m also showing you how to change the pitch on an added sound to a trigger event.
Do you enjoy the content?
Feel free to share it with your friends!
Источник
String Handling
An overview of the string classes available in UE4 and reference guides for FName, FText, and FString.
FName
When you name a new asset in the Content Browser, change a parameter in a Dynamic Material Instance, or access a bone in a Skeletal Mesh, you are using FNames. FNames provide a very lightweight system for using strings, where a given string is stored only once in a data table, even if it is reused.
FNames are case-insensitive. They are immutable, and cannot be manipulated. The storage system and static nature of FNames means that it is fast to look up and access FNames with keys. Another feature of the FName subsystem is the use of a hash table to provide fast string to FName conversions.
FText
In Unreal Engine 4 (UE4) the primary component for text localization is the FText class. All user-facing text should use this class, as it supports text localization by providing the following features:
Formatting Text (to generate text from a placeholder pattern).
Generating derived text , such as making text upper or lower case.
FText also features the AsCultureInvariant function (or the INVTEXT macro), which creates non-localized, or «culture invariant» text. This is useful for things like converting a player name from an external API into something you can display in your user interface.
You can create a blank FText using either FText::GetEmpty() , or by using just FText() .
FString
Unlike FName and FText , FString can be searched, modified, and compared against other strings. However, these manipulations can make FStrings more expensive than the immutable string classes. This is because FString objects store their own character arrays, while FName and FText objects store an index to a shared character array, and can establish equality based purely on this index value.
Printf
The FString function, Printf , can create FString objects the format argument specifiers as the C++ printf function. Similarly, the UE_LOG macro prints a printf formatted string to the screen, log output, and log files, depending on what type of UE4 build is running.
Remember that to use these strings and conversion you will need to include the necessary header files. A list of which header files are needed can be found on the API reference page for each string.
Источник
Основные приёмы Blueprint-программирования, часть 2
В прошлой статье мы с тобой рассмотрели базовые ноды для программирования на Blueprints. И сегодня окунёмся в более интересные приёмы.
Первым делом начнём с самых популярных функций и затем переберёмся к остальным нодам FlowControl.
Print String
Функция печатает строку, которая приходит в пин InString. Есть соответственные bool-параметры для отображения на экране или в логе, настройка цвета текста (Text Color) и длительность пребывания на экране игры в секундах (Duration).
Это очень полезная и, пожалуй, самая часто используемая функция при разработке. С её помощью можно мониторить результаты выполнения алгоритмов прямо во время работы приложения. Кроме вывода собственных сообщений — можно так же выводить имена объектов, количество элементов массива и, в целом, абсолютно всё, что можно так или иначе прочитать и преобразовать в тип переменной String.
Delay, Retriggerable Delay
Эти функции приостанавливают выполнение ветки событий, к которым подключены. Остановка начинается в тот момент, когда сигнал приходит в ноду. Есть два типа — просто Пауза (Delay) и возобновляемая пауза (Retriggerable Delay). Разница в том, что если в Retriggerable Delay придёт новый сигнал пока пауза не кончится — то отсчёт времени начнётся заново. В случае с простым Delay — ему будет побоку, отсчёт времени паузы не изменится.
Delay может использоваться, например когда вы жмёте на кнопку запуска ракеты — нажали и пошёл обратный отсчёт до запуска двигателей.
Retrigerable Delay — может, например, использоваться в моментах игры, когда надо часто и быстро нажимать на одну и ту же кнопку. Наверняка знаете такие моменты, когда надо унажиматься, чтобы персонаж открыл дверь или приложил усилия) В первый раз при нажатии на кнопку активируется Retriggerable Delay и при повторных нажатиях счётчик паузы сбрасывается. Если недостаточно часто нажимать, то пауза успеет закончиться и пойдёт дальнейшее выполнение алгоритма, например — катим валун и недостаточно часто нажимаем на кнопку и валун нас придавил)) Но это уже другая история)
Кстати! Заметьте, что в правом верхнем углу есть значок времени, который обозначает привязку функции ко времени. Такие функции в UE4 называются Latent-функциями, т.е. продолжительными (дословно: скрытая функция, дословный перевод тут не особо подходит).
Gate переводится как «Ворота». Работает нода таким же образом: есть вход (1) и есть состояния открытых/закрытых дверей. Открывая двери (2) мы пропускаем выполнение алгоритма сквозь эту ноду и выполняются дальнейшие операции (5). Закрывая двери (3) мы блокируем выполнение алгоритма и он останавливается на этой ноде. Так же мы можем просто переключить статус открытости-закрытости пустив сигнал в пин Toggle (4). Булевым параметром Start Closed мы можем регулировать изначальное состояние этой ноды (закрытое/открытое) на старте работы приложения.
Часто используется в связке с повторяющимися операциями и напоминает эдакий вентиль. К вентилю поступает вода и мы можем его отрыть и закрыть, тем самым пуская и останавливая поток воды.
Вот небольшой пример:
Event Tick вызывается каждый раз, когда отрисовывается кадр игры.
При нажатии на пробел — Gate пропускает сигнал и переменная Counter увеличивается на единицу. Отпускаем пробел — увеличение переменной останавливается. Так мы можем посмотреть сколько кадров было отрисовано программой пока мы держали пробел нажатым. Не самое практичное использование, но суть вы уловили 😉
MultiGate
Когда в ноду приходит сигнал — то один раз выполняется один из её выходных пинов. При повторном сигнале — выполняется следующий пин. Если мы поставим параметр Is Random — каждый вызываемый пин будет случайным. Как только мы перебрали все пины — нода перестаёт функционировать. Но мы можем прислать сигнал в Reset и «освежить» ноду, она начнёт своё функционирование сначала.
Параметр Start Index указывает с какого индекса надо начать выполнение. Если мы отмечаем галочкой Is Random, то в индексе отпадает смысл и он попросту не учитывается, а пины вызываются в случайном порядке.
Если мы отметим параметр Loop — то после выполнения всех Out пинов — выполнение начнётся по-новой.
Sequence
В блупринтах есть такое правило: в один пин может прийти сколько угодно связей, а вот выходить из Executable-пинов может только одна. Хотя иногда очень нужно запустить сразу несколько операций, и для этого есть нода Sequence — которая по порядку выполняет свои пины. На скриншоте справа — аналог выполнения ноды Sequence. Но здесь есть одна штука: когда мы используем Latent-функции, то Sequence их не учитывает. Вот пример:
Если мы будем использовать Latent-функции, то вызов пинов ноды Sequence не будет ждать их выполнения и в результате такой вариант будет работать примерно так:
То есть, сначала выполнятся все выходные пины и операции, расположенные до Latent-функции Delay, а всё что находится после — с указанной задержкой.
В общем случае эта нода используется для организации алгоритма и контролирует выполнения ваших блоков задач. Например, когда взрывается граната надо 1) Включить систему частиц со взрывом, 2) Воспроизвести звук, 3) Разрушить всё к чертям, 4) Убить врагов если они рядом стояли, 5) Начислить очки за взрыв. Эти вещи можно пустить в последовательное выполнение, но это неудобно. Здесь на помощь и придёт нода Sequence.
DoOnce
Довольно простая нода, которая даёт выполнить алгоритм, соединённый с пином Completed только 1 раз. При необходимости можно сбрасывать ноду, пустив сигнал в пин Reset — тогда она ещё 1 раз пропустит сигнал сквозь себя и запустит выполнение того, что соединено с Completed-пином.
Так же как и в ноде Gate здесь есть параметр, указывающий состояние ноды на момент старта игры Start Closed.
Например, игрок может получить бонус только один раз, тогда используем эту ноду и при повторных попытках игрок ничего не получит.
Русские названия в функциях и событиях я использую ради примера — в своих проектах используйте английский язык.
Работа ноды очень похожа на DoOnce, только она позволяет N раз выполнить алгоритм, который стоит после неё (соединён с Exit). Когда произошло N-выполнений, нода закрывается и не пропускает сигнал сквозь себя. Ну и так же как раньше, можно пустить сигнал в Reset (сбросить ноду), чтобы счётчик обнулился и она снова могла пропустить N вызовов.
Switch On Int, Switch On String
Это переключатель, который выполняет тот или иной выходной пин, в зависимости от того, что пришло параметром на вход (Selection).
Редактировать варианты можно на вкладке Details
Например, для каждого героя должен выполняться свой алгоритм. И с помощью такой выборки можно для каждого героя настроить собственную логику.
Default-пин выполняется, если на вход пришёл параметр, для которого нет варианта.
Switch On Int подробно расписывать не буду — он работает так же, только использует не строку, а целое число.
Заключение
Мы разобрали основные ноды для контроля выполнения алгоритмов в движке Unreal Engine 4. Но знать набор нод или функций недостаточно для написания по-настоящему хороших программ или игр. Надо уметь так же грамотно составлять архитектуру приложения.
Если тебя заинтересовал такой подход к программированию и ты хотел бы всерьёз овладеть Blueprint’ами и обучиться современной и востребованной профессии, то предлагаю обратить внимание на самый мощный в рунете курс про грамотное создание программ в Unreal Engine 4 — курс BlueprintME!
Этот курс я специально составил так, чтобы ты не просто заучил несколько функций и приёмов, а полностью понял как создаются программы и смог самостоятельно и грамотно написать любой алгоритм любой сложности.
Для кого этот курс?
+ Для 3D-дизайнеров, которые хотят создавать не просто модели, но и делать из них компьютерные игры
+ Для Архитекторов-визуализаторов, которые устали от долгих рендеров и правок заказчиков. Делайте интерактивные презентации, повышайте ценность своей работы =)
+ Для Инди-разработчиков, которые приступили или продолжают работу над своей игрой, но боятся, что из-за незнания тонкостей наговнокодят и посреди разработки придётся начинать всё переделывать.
+ Для программистов, которые устали от скучной работы и мечтают применить свой опыт в более интересном направлении, создавая зрелищные приложения и игры.
+ Для Геймеров, которые бы могли создавать крутейшие игры, если бы только знали как)
Что ты получишь по окончанию BlueprintME!:
1) Избавишься от каши в голове, если до этого обучался по видео с ютуба.
2) Получишь ценный опыт и навыки, которые равнозначны 2+ годам самостоятельного обучения.
3) Будешь грамотно придумывать алгоритмы любой сложности и выбирать наилучший.
4) Создашь сложный игровой проект, который высоко оценят при трудоустройстве и который откроет глаза на разработку в целом.
5) Получишь сертификат и возможность трудоустройства в компании-партнёры курсов, где сможешь прокачиваться далее бок о бок с профессионалами.
На курс можно идти «с нуля», это значит, что если ты никогда не работал с движком, я дам вводный материал, который поможет быстро освоиться и начать работу.
На курсе я лично помогаю каждому разобраться со всеми возникающими вопросами в формате переписок, видеоответов и связи по Skype и TeamViewer.
Переходи по этой → ссылке ←, чтобы получить подробности курса в личные сообщения. Чат бот расскажет детали, но так же я общаюсь там лично, так что велкам.
Ещё раз, вот ссылка → https://vk.cc/ajcdmn
Вознаграждение за любознательность 🙂
Каждому кто прочитал статью полагается скидка за любознательность =) Используй промокод cool-blueprints для скидки в 1000р на курс)
Спасибо за внимание и до скорой встречи! =)
Источник