String unity что значит

String

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

Represents text as a series of Unicode characters.

Unity uses the .Net System.String class for strings. See the Microsoft MSDN documentation for Strings for more details.

Note: In c# string is an alias for System.String . This means that you can use either string or String in your code (if you have added using System to the top of your script.) Note: In Javascript strings are represented using String which you should use in your Unity script code. Here are some basic uses of the String class.

Читайте также:  Что значит ввп по паритету покупательной способности

This example shows how you can examine the String class and see the methods it contains.

Variables

Empty Represents the empty string. (Read Only)
Length Gets the number of characters in this instance (Read Only).

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright © 2017 Unity Technologies. Publication: 5.6-001N. Built: 2017-07-12.

Источник

Strings and text

Handling strings and text is a common source of performance problems in Unity projects. In C#, all strings are immutable You cannot change the contents of an immutable (read-only) package. This is the opposite of mutable. Most packages are immutable, including packages downloaded from the package registry or by Git URL.
See in Glossary . Any manipulation of a string results in the allocation of a full new string. This is relatively expensive, and repeated string concatenations can develop into performance problems when performed on large strings, on large datasets, or in tight loops.

Further, as N string concatenations require the allocation of N–1 intermediate strings, serial concatenations can also be a major cause of managed memory pressure.

For cases where strings must be concatenated in tight loops or during each frame, use a StringBuilder to perform the actual concatenation operations. The StringBuilder instance can also be reused to further minimize unnecessary memory allocation.

Microsoft maintains a list of best practices for working with strings in C#, which can be found here on the MSDN website: msdn.microsoft.com.

Locale coercion and ordinal comparisons

One of the core performance problems often found in string-related code is the unintended use of the slow, default string APIs. These APIs were built for business applications, and attempt to deal with handling strings from many different cultural and linguistic rules with regards to the characters found in text.

For example, the following example code returns true when run under the US-English locale, but returns false for many European locales(1)

NOTE: Note that, as of Unity 5.3 and 5.4, Unity’s scripting runtimes always run under the US English (en-US) locale:

For most Unity projects, this is entirely unnecessary. It is roughly ten times faster to use the ordinal comparison type, which compares strings in a manner familiar to C and C++ programmers: by simply comparing each sequential byte of the string, without regard for the character represented by that byte.

Switching to ordinal string comparison is as simple as supplying StringComparison.Ordinal as the final argument to String.Equals :

Inefficient built-in string APIs

Beyond switching to ordinal comparisons, certain C# String APIs are known to be extremely inefficient. Among these are String.Format , String.StartsWith and String.EndsWith. String.Format is difficult to replace, but the inefficient string comparison methods are trivially optimized away.

While Microsoft’s recommendation is to pass StringComparison.Ordinal into any string comparison that does not need to be adjusted for localization, Unity benchmarks show that the impact of this is relatively minimal compared to a custom implementation.

Method Time (ms) for 100k short strings
String.StartsWith , default culture 137
String.EndsWit h, default culture 542
String.StartsWith , ordinal 115
String.EndsWith , ordinal 34
Custom StartsWith replacement 4.5
Custom EndsWith replacement 4.5

Both String.StartsWith and String.EndsWith can be replaced with simple hand-coded versions, similar to the example attached below.

Regular Expressions

While Regular Expressions are a powerful way to match and manipulate strings, they can be extremely performance-intensive. Further, due to the C# library’s implementation of Regular Expressions, even simple boolean IsMatch queries allocate large transient datastructures “under the hood.” This transient managed memory churn should be deemed unacceptable, except during initialization.

If regular expressions are necessary, it is strongly recommended to not use the static Regex.Match or Regex.Replace methods, which accept the regular expression as a string parameter. These methods compile the regular expression on-the-fly and do not cache the generated object.

This example code is an innocuous one-liner.

However, each time it’s executed, it generates 5 kilobytes of garbage. A simple refactoring can eliminate much of this garbage:

In this example, each call to myRegExp.Match “only” results in 320 bytes of garbage. While this is still expensive for a simple matching operation, it is a considerable improvement over the previous example.

Therefore, if the regular expressions are invariant string literals, it is considerably more efficient to precompile them by passing them as the first parameter of the Regex object’s constructor. These precompiled Regexes should then be reused.

XML, JSON and other long-form text parsing

Parsing text is often one of the heaviest operations that occurs at loading time. In some cases, the time spent parsing text can outweigh the time spent loading and instantiating Assets.

The reasons behind this depend on the specific parser used. C#’s built-in XML parser is extremely flexible, but as a result, it is not optimizable for specific data layouts.

Many third-party parsers are built on reflection. While reflection is an excellent choice during development (because it allows the parser to rapidly adapt to changing data layouts), it is notoriously slow.

Unity has introduced a partial solution with its built-in JSONUtility API, which provides an interface to Unity’s serialization system that reads/emits JSON. In most benchmarks, it is faster than pure C# JSON parsers, but it has the same limitations as other interfaces to Unity’s serialization system – it cannot serialized many complex data types, such as Dictionaries, without additional code(2) (NOTE: See the ISerializationCallbackReceiver interface for one way to easily add the additional processing necessary to convert to/from complex data types during Unity’s serialization process.).

When encountering performance problems that arise from textual data parsing, consider three alternative resolutions.

Option 1: Parse at build time

The best way to avoid the cost of text parsing is to entirely eliminate the parsing of text at runtime. In general, this means “baking” the textual data into a binary format via some sort of build step.

Most developers who opt for this route move their data to some sort of ScriptableObject-derived class hierarchy and then distribute the data via AssetBundles. For an excellent discussion of using ScriptableObjects, see Richard Fine’s Unite 2016 talk on youtube.

This strategy offers the best possible performance, but is only suitable for data that does not need to be generated dynamically. It is best suited for game design parameters and other content.

Option 2: Split and lazy load

A second possibility is to split up the data that must be parsed into smaller chunks. Once split, the cost of parsing the data can be spread across several frames. In the ideal case, identify the specific portions of the data that are required to present the desired experience to the user and load only those portions.

In a simple example: if the project were a platform game, it would not be necessary to serialize data for all the levels together into one giant blob. If the data were split into individual Assets for each level, and perhaps segmented the levels into regions, the data could be parsed as the player approached it.

While this sounds easy, in practice it requires a substantial investment in tool code and may require data structures to be reorganized.

Option 3: Threads

For data that is parsed entirely into plain C# objects, and does not require any interaction with Unity APIs, it is possible to move the parsing operations to worker threads.

This option can be extremely powerful on platforms with a significant number of cores(3) (NOTE: Note that iOS Apple’s mobile operating system. More info
See in Glossary devices have at most 2 cores. Most Android devices have 2–4. This technique of more interest when building for standalone and console build targets.) However, it requires careful programming to avoid creating deadlocks and race conditions.

Projects that choose to implement threading generally use the built-in C# Thread and ThreadPool classes (see msdn.microsoft.com) to manage their worker threads, along with the standard C# synchronization classes.

Footnotes

(1) Note that, as of Unity 5.3 and 5.4, Unity’s scripting runtimes always run under the US English (en-US) locale.

(2) See the ISerializationCallbackReceiver interface for one way to easily add the additional processing necessary to convert to/from complex data types during Unity’s serialization process.

(3) Note that iOS devices have at most 2 cores. Most Android devices have 2–4. This technique is of more interest when building for standalone and console build targets.

Источник

unity3d Optimization Strings

Example

One might argue that there are greater resource hogs in Unity than the humble string, but it is one of the easier aspects to fix early on.

String operations build garbage

Most string operations build tiny amounts of garbage, but if those operations are called several times over the course of a single update, it stacks up. Over time it will trigger the automatic Garbage Collection, which may result in a visible CPU spike.

Cache your string operations

Consider the following example.

It may look silly and redundant, but if you’re working with Shaders, you might run into situations such as these. Caching the keys will make a difference.

Please note that string literals and constants do not generate any garbage, as they are injected statically into the program stack space. If you are generating strings at run-time and are guaranteed to be generating the same strings each time like the above example, caching will definitely help.

For other cases where the string generated is not the same each time, there is no other alternative to generating those strings. As such, the memory spike with manually generating strings each time is usually negligible, unless tens of thousands of strings are being generated at a time.

Most string operations are Debug messages

Doing string operations for Debug messages, ie. Debug.Log(«Object Name: » + obj.name) is fine and cannot be avoided during development. It is, however, important to ensure that irrelevant debug messages do not end up in the released product.

One way is to use the Conditional attribute in your debug calls. This not only removes the method calls, but also all the string operations going into it.

This is a simplified example. You might want to invest some time designing a more fully fledged logging routine.

String comparison

This is a minor optimisation, but it’s worth a mention. Comparing strings is slightly more involved than one might think. The system will try to take cultural differences into account by default. You can opt to use a simple binary comparison instead, which performs faster.

Источник

String unity что значит

Рисование, Дизайн и Разработка игр

Главная » Unity3D: Основы использования скриптов для новичков: Подробнее о переменных

Unity3D: Основы использования скриптов для новичков: Подробнее о переменных

Переменные и свойства компонентов Unity3D

Игровые объекты, которые вы создаете, будут иметь определенные свойства, создающие из игровых объектов то, чем они являются. Когда вы добавляете компонент к игровому объекту, то вы изменяете или дополняете его поведение. Это означает, конечно же, что определенная информация, добавляемая конкретным компонентом, добавляется к игровому объекту, должна быть сохранена где-то внутри компонента. Такая информация или данные сохраняются в переменных .

Переменные становятся свойствами компонента

Это настройка скрипта Soldier Controller (SoldierController.js)

  1. Слева находятся свойства компонента, представленные в окне Inspector среды разработки Unity.
  2. Справа — скрипт в редакторе скиптов Unitron.

Начинайте имя переменной со знаков нижнего регистра

Как видите, первая буква имени каждой переменной начинается со строчной буквы.

Сложносоставные имена переменных

  1. Имена переменных могут быть в длину только одного слова, без пробелов. Поэтому, если вы желаете сделать имена переменных , которые бы были больше одного слова в длину, то нужно, чтобы вы сжали все слова вместе в своем скрипте, например runSpeed. Имя начинается с маленькой буквы, а каждое дополнительное слово начинается с большой буквы.
  2. Unity выполняет немного магии и превращает runSpeed в имя свойства Run Speed.

  1. В скрипте значение равно 3.07
  2. В инспекторе значение равно 4.53

Что-то было сделано не правильно? Нет, все правильно. Значения, которые вы назначаете переменным в скриптах, считаются значениями по умолчанию. Вы можете поправить значения в окне инспектора для получения более приемлемого поведения игрового объекта. Кроме того, такие поправки, устанавливаемые вами, сохраняются, означая, что вам не нужно будет постоянно вносить изменения в свой скрипт.

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

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

Вы можете сбросить значения в инспекторе

Чтобы обнулить значения в окне инспектора на первичные значения в скрипте:

  1. Нажмите на шестеренку;
  2. Нажмите Reset

Такие действия изменят значения свойств в инспекторе на первоначальные, определенные в скрипте.

Имена переменных и слово «type»

Как и в примере с почтовым ящиком, где я давал раннее представление о том, какие различные типы вещей могут находиться в почтовом ящике, переменные также могут содержать различные типы (прим. ред. — types) данных. Они могут содержать все что угодно, от простых чисел, таких как число 3, до целых игровых объектов и префабов.

Чтобы добавить переменные в скрипт, существует некоторая простая грамматика, которую вы должны усвоить.

Объявление переменных в скрипте

Каждая переменная , которую вы хотите использовать в скрипте, должна быть объявлена в разделе деклараций. Что это значит? Укажите Unity то, что вы хотите создать так, чтобы система Unity знала, что это такое, когда вы будете использовать это в своем скрипте. Взгляните на строчку 4.

Я создал переменную с именем easyName. Справа перед ней находится ключевое слово var, которое, конечно же, является аббревиатурой слова » variable «. Помещая var, мы указываем Unity то, что создаем новую переменную .

Следовательно, перед тем как Unity сможет использовать любую переменную , которую мы хотим, мы должны указать Unity сначала об этом. Указание Unity переменной называется объявлением переменной , которое вы можете сделать только один раз. Теперь переменная easyName может быть использована где угодно в скрипте.

Обратите внимание, что объявление заканчивается точкой с запятой. Все объявления должны заканчиваться точкой с запятой, иначе, Unity не сможет понять, где заканчивается выражение, а где начинается новое. Так же, как использование точки в конце предложения. Вы когда-нибудь пробовали прочитать целую группу предложений без каких-либо точек? Может быть не просто. Вы бы поняли это, поскольку умны. Но Unity не может, потому что является всего лишь скромной компьютерной программой.

Еще одна очень важная вещь, которую вы должны запомнить, и которая, возможно, приведет к программным ошибкам. Во всем этом коде, который вы видите, довольно много знаков равенства (=). В программировании и в скриптах, это не знак равенства, а оператор присваивания. Поэтому, когда вы видите:

То это не означает, что переменная easyName равна 10. Это означает то, что переменной easyName присваивается значение 10.

Я расскажу о равенстве в следующем уроке.

Основные типы переменных

Вышеперечисленные типы являются самыми распространенными типами переменных практически в любом языке программирования.

Слово «Type» для переменной

Взгляните на строку 6. У этого выражения объявления что-то добавлено в конце. Что это за слово int?

Хорошо, взгляните на таблицу выше и посмотрите, что это слово означает integer.

Я создал переменную с именем easyNameTyped, за которой следует двоеточие, а затем int.

В системе скриптов Unity, вот как вы указываете Unity о том, что хотите, чтобы переменная содержала конкретный тип данных. Используйте двоеточие, за которым следует тип. Я специально указал Unity, что эта переменная должна будет содержать целочисленное значение, целое число.

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

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

Приведение типов

Вернемся к строке 4, а также к строке 5.

Когда я объявил переменную easyName, то не указал ее тип, и Unity на самом деле не заботится об этом, потому что easyName не используется в скрипте вообще, а только объявляется, что является переменной . В строке 5 easyName используется в первый раз и ей назначается целочисленное значение, число 10. Теперь Unity знает, какой тип значений для переменной easyName будет позволено сохранять.

Вот как работает приведение типов. Тип определяется посредством того, как он используется первый раз в скрипте. С этого момента, когда игра работает, любое число, которое скрипт помещает в переменную easyName, даже десятичные числа, такие как 2.3, Unity сотрет часть со значением .3 и допустит только целочисленную часть значения, в этом случае 2.

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

Способ заставить вас указывать типы — добавить #pragma strict в скрипт в качестве самой первой строки.

Примечание: Каждый раз, когда переменная появляется в скрипте после того, как она была объявлена при помощи слова var, вот такое использование данный переменной , как в строке 5.

Тип float

Строка 15 является переменной с типом float. Это означает, что переменная будет сохранять десятичное число, которое содержит десятичную точку.

В данном примере я указал переменную withFloatTyped как десятичную в разделе объявлений, поэтому Unity знает наверняка, что может содержать переменная. Я также назначил переменной значение в разделе объявлений.

Если бы я просто назначил переменной значение 7, то для Unity оно было бы фактически равно 7.0 .

Тип boolean

Что это еще за тип boolean?

В окне инспектора Unity данный тип представлен в виде переключателя. Поэтому переменная типа boolean может иметь значение либо true либо false, отмечено или не отмечено.

Мы рассмотрим применение значений true и false позднее, когда доберемся до принятия решений в скриптах.

Тип String

Обратите внимание, что определяя переменную simpleStringTyped как переменную типа String, слово String начинается с большой буквы, а не с маленькой. Все потому что тип String является классом. Другие типы, int, float и boolean просто встроены как часть системы скриптового языка Unity.

Имена всех классов начинаются с большой буквы. Мы ознакомимся еще с объявлением переменных в качестве типов-классов позже, с такими как класс Transform, например.

Заключайте символы в двойные кавычки, чтобы сформировать строку из них.

Общедоступные переменные

Переменные , которые я создал, являются общедоступными переменными , это означает то, что значения, которые содержатся в них, — доступны из других скриптов. Они также могут отображаться в окне инспектора Unity. Только одно замечание было к строке 4. Я не объявил тип для переменной easyName, поэтому система Unity не смогла добавить ее в инспектор. Unity не имеет понятия, какой тип переменной добавить, поэтому и не добавляет вообще.

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

Скрытые переменные

Я немного изменил строку 12. Я добавил слово private перед var. Оно означает то, что переменная withIntTyped не доступна для других скриптов. Ее может использовать только скрипт TeachMe.

Скрытые переменные не отображаются в окне инспектора Unity

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

Вывод

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

  1. Нужно или нет, чтобы переменная была общедоступной или скрытой?
  2. Писать слово var.
  3. Создавать имя для переменной .
  4. Указывать тип.
  5. Следует ли назначать значение сразу или позже в скрипте или инспекторе?
  6. Закрывать переменную точкой с запятой.

Источник

Оцените статью