Академический Документы
Профессиональный Документы
Культура Документы
public class HelloWorld : MonoBehaviour {
// Use this for initialization
void Start () {
print ("Hello World");
}
// Update is called once per frame
void Update () {
}
}
print ("Hello World");-выведит в консоль строку с текстом
"Hello World" Тоесть просто выведит в строку текст "Hello World"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HelloWorld : MonoBehaviour {
// Use this for initialization
void Start () {
//print ("Hello World");
}
// Update is called once per frame
void Update () {
print ("Hello World");
}
}
public class CubeSpawner : MonoBehaviour {
public GameObject cubePrefabVar;
// Используйте этот метод для инициализации
void Start () {
//Instantiate( cubePrefabVar );
}
// Update вызывается в каждом кадре
void Update () {
Instantiate( cubePrefabVar );
}
}
Выберите объект Ground в панели Scene (Сцена) или Hierarchy
(Иерархия), нажмите клавишу W, Е или R, чтобы переместить,
повернуть или изменить масштаб игрового объекта.
india = 8;
Transform trans =
gObj.GetComponent<Transform>( ); // Определение
ссылки trans на компонент Transform объекта gObj
|| (оператор ИЛИ)
! - NOT
& - И с полной схемой вычислений / поразрядное И
&& - И
|| - ИЛИ
( а & b ) эквивалентно ! ( !а | !b )
( а | b ) эквивалентно ! ( !а & !b )
== (равно)
bool f = false;
bool t = true;
print( f == t ); // выведет: false
int i0 = 10;
int i1 = 10;
int i2 = 20;
float f0 = 1.23f;
float f1 = 3.14f;
float f2 = Mathf.PI;
!= (не равно)
Инструкция if
Инструкция if выполняет код в фигурных скобках {}, только если
значение в круглых скобках () вычисляется как true:
if (true) {
if (false) {
Если какое-то из условий в цепочке if.. .else if.. .else вычисляется как
true, все остальные условия не проверяются (остальная часть
цепочки просто пропускается).
Циклы
Цикл while: самый простой вид цикла. Перед каждой итерацией
проверяет условие, чтобы убедиться, что можно продолжить
выполнять цикл.
Цикл while
Бесконечный цикл
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
while (true) {
print ("Loop");
}
}
// Update is called once per frame
void Update () {
}
}
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
int i = 0;
while (i<3) {
print ("Loop:" + i);
i++;
}
}
// Update is called once per frame
void Update () {
}
}
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
int i = 1;
print (i); //Выведет: 1
print(i++); //Выведет: 1
print(i); //Выведет: 2
print(++i); //Выведет: 3
}
// Update is called once per frame
void Update () {
}
}
Цикл do...while
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
int i = 10;
do {
print ("Loop: " + i);
} while(i < 3);
}
// Update is called once per frame
void Update () {
}
}
Цикл for
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
for (int i = 0; i < 3; i++) {
print ("Loop: " + i);
}
}
// Update is called once per frame
void Update () {
}
}
for (int i = 0; i < 3; i++) {
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
for (int i = 5; i > 2; i--) {
print ("Loop: " + i);
}
}
// Update is called once per frame
void Update () {
}
}
Цикл foreach
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
string str = "Hello";
foreach (char chr in str) {
print (chr);
}
}
// Update is called once per frame
void Update () {
}
}
Инструкция break
Инструкция break может также использоваться в любых циклах для
преждевременного выхода из них.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
for (int i = 0; i < 10; i++) {
print (i);
if (i == 3) {
break;
}
}
}
// Update is called once per frame
void Update () {
}
}
int i = 0; 0
while (true) { 1
print (i); 2
if (i > 2) break; 3
i++;
}
int i = 3; 3
do { 2
print (i);
i--;
if (i == 1)
break;
} while (i > 0);
foreach (char c in "Hello") { H
if (c == 'l') { e
break;
}
print (c);
}
Инструкция continue
Инструкция continue заставляет программу пропустить код,
оставшийся в теле цикла, и начать следующую итерацию.
Код: Вывод:
for (int i = 0; i <= 360; i++) 0
{ 90
if (i % 90 != 0) { 180
continue; 270
} 360
print (i);
}
Список List*: тип List (или список) напоминает массив, но, в отличие
от последнего, его размер не фиксирован и лишь немного уступает
ему в производительности.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ListEx : MonoBehaviour {
public List<string> sList;
// Use this for initialization
void Start () {
sList = new List<string> ();
sList.Add ("Experience");
sList.Add ("is");
sList.Add ("what");
sList.Add ("you");
sList.Add ("get");
sList.Add ("when");
sList.Add ("you");
sList.Add ("don't");
sList.Add ("get");
sList.Add ("what");
sList.Add ("you");
sList.Add ("wanted");
print ("sList Count = " + sList.Count);//sLis
t Count = 12
print ( "The 0th element is: " + sList[0]); /
/The 0th element is: Experience
print ( "The 1st element is: " + sList[1]); /
/The 1st element is: is
print ( "The 3rd element is: " + sList[3]); /
/The 3rd element is: you
print ( "The 8th element is: " + sList[8]); /
/The 8th element is: get
string str = "";
foreach( string sTemp in sList) {
str += sTemp + " ";
}
print (str); //Experience is what you get whe
n you don't get what you wanted
}
// Update is called once per frame
void Update () {
}
}
x += y
эквивалентно
x=x+y
List
Свойства
Свойства возвращают информацию о списке List
Методы
Методы — это функции, позволяющие изменять список
Dictionary
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DictionaryEx : MonoBehaviour {
public Dictionary<string,string> statesDict;
// Use this for initialization
void Start () {
statesDict = new Dictionary<string,string> ();
statesDict.Add ("MD", "Maryland");
statesDict.Add ("TX", "Texas");
statesDict.Add ("PA", "Pennsylvania");
statesDict.Add ("CA", "California");
statesDict.Add ("MI", "Michigan");
print ("There are " + statesDict.Count + " el
ements in statesDict.");//There are 5 elements in sta
tesDict.
foreach (KeyValuePair<string,string> kvp in
statesDict) {
print (kvp.Key + ": " + kvp.Value);//MD:M
aryland TX:Texas PA:Pennsylvania ...
}
print ("MI is " + statesDict ["MI"]);//MI is
Michigan
statesDict ["BC"] = "British Columbia";
foreach (string k in statesDict.Keys) {
print (k + " is " + statesDict [k]);//BC
is British Columbia MI is Michigan TX is Texas
}
}
// Update is called once per frame
void Update () {
}
}
foreach (KeyValuePair<string,string> kvp in
statesDict) {
print (kvp.Key + ": " + kvp.Value);//MD:M
aryland TX:Texas PA:Pennsylvania ...
}
Для обхода элементов словаря можно использовать цикл foreach,
но переменная цикла в этом случае должна иметь тип
KeyValuePair<,>.Два типа в угловых скобках KeyValuePair<,> должны
совпадать с типами, указанными в объявлении переменной
словаря (в данном примере <string,string> ).
foreach (string k in statesDict.Keys) {
print (k + " is " + statesDict [k]);//BC
is British Columbia MI is Michigan TX is Texas
}
public Dictionary<int,string> dIS;
dIS = new Dictionary<int, string>();
dIS[0] = "Zero";
dIS[1] = "One";
dIS[10] = "Ten";
dIS[1234567890] = "A lot!";
public Dictionary<int,string> dIS;
dIS = new Dictionary<int, string> () {
{ 0, "Zero" },
{ 1, "One" },
{ 10, "Ten" },
{ 1234567890, "A lot!" }
};
Массивы
Массив — простейший и самый быстрый тип коллекций. Для
работы с массивами не требуется импортировать дополнительные
библиотеки (инструкцией using), потому что они встроены в ядро
языка С#. Кроме того, массивы могут быть многомерными и
ступенчатыми, что иногда очень удобно.
public class ArrayEx : MonoBehaviour {
public string[] sArray;
// Use this for initialization
void Start () {
sArray = new string[10];
sArray[0] = "These";
sArray[1] = "are";
sArray[2] = "some";
sArray[3] = "words";
print ("The length of sArray is: " + sArray.L
ength);//The length of sArray is: 10
string str = "";
foreach (string sTemp in sArray) {
str += "|" + sTemp;
}
print (str);//|These|are|some|words||||||
}
// Update is called once per frame
void Update () {
}
}
public class ArrayEx : MonoBehaviour {
public string[] sArray;
// Use this for initialization
void Start () {
sArray = new string[10];
sArray[0] = "These";
sArray[1] = "are";
sArray[2] = "some";
sArray[3] = "words";
print ("The length of sArray is: " + sArray.L
ength);//The length of sArray is: 10
string str = "";
foreach (string sTemp in sArray) {
str += "|" + sTemp;
if (sTemp == null)
break;
}
print (str);//|These|are|some|words|
}
// Update is called once per frame
void Update () {
}
}
Свойства
sA.Length: вернет общий размер массива. Учитываются все
элементы, независимо от того, было им присвоено какое-то
значение или они все еще хранят значение по умолчанию.
Статические методы
Статические методы массивов являются частью класса System.Array
(то есть определены в библиотеке System.Collections) и добавляют
в массивы некоторые возможности, свойственные спискам List.
Многомерные массивы
При работе с многомерными массивами в квадратных скобках
можно вместо одного использовать два или более индекса. Таким
способом можно создать двумерную таблицу с элементами-
ячейками.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Array2dEx : MonoBehaviour {
public string[,] sArray2d;
// Use this for initialization
void Start () {
sArray2d = new string[4,4];
sArray2d[0,0] = "A";
sArray2d[0,3] = "B";
sArray2d[1,2] = "C";
sArray2d[3,1] = "D";
print ("The Length of sArray2d is: " + sArray
2d.Length);//The Length of sArray2d is: 16
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Array2dEx : MonoBehaviour {
public string[,] sArray2d;
// Use this for initialization
void Start () {
sArray2d = new string[4,4];
sArray2d[0,0] = "A";
sArray2d[0,3] = "B";
sArray2d[1,2] = "C";
sArray2d[3,1] = "D";
print ("The Length of sArray2d is: " + sArray
2d.Length);//The Length of sArray2d is: 16
string str = "";
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (sArray2d [i, j] != null) {
str += "|" + sArray2d [i, j];
} else {
str += "|_";
}
}
str += "|" + "\n";
}
print (str);
}
// Update is called once per frame
void Update () {
}
}
The Length of sArray2d is: 16
|A|_|_|B|
|_|_|C|_|
|_|_|_|_|
|_|D|_|_|
Ступенчатые массивы
Ступенчатый массив — это массив массивов. Он напоминает
многомерный массив, но может иметь вложенные массивы разной
длины.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JaggedArrayEx : MonoBehaviour {
public string[][] jArray;
// Use this for initialization
void Start () {
jArray = new string[4][];
jArray[0] = new string[4];
jArray[0][0] = "A";
jArray[0][1] = "B";
jArray[0][2] = "C";
jArray[0][3] = "D";
//Примеры инициализации массива в одной строк
е
jArray[1] = new string[] {"E", "F", "G"};
jArray[2] = new string[] { "H", "I" };
jArray[3] = new string[4];
jArray[3][0] = "J";
jArray[3][3] = "K";
print ("The Length of jArray is: " + jArray.L
ength);
//Выведет: The Length of jArray is: 4
print ("The Length of jArray[1] is: " + jArra
y [1].Length);
//Выведет: The Length of jArray[1] is: 3
string str = "";
foreach (string[] sArray in jArray) {
foreach (string sTemp in sArray) {
if (sTemp != null) {
str += " | " + sTemp;
} else {
str += " | ";
}
}
str += " | \n";
}
print(str);
}
// Update is called once per frame
void Update () {
}
}
|A|B|C|D|
|E|F|G|
|H|I|
|J| | |K|
public class JaggedArrayEx : MonoBehaviour {
public string[][] jArray;
// Use this for initialization
void Start () {
jArray = new string[4][];
jArray[0] = new string[4];
jArray[0][0] = "A";
jArray[0][1] = "B";
jArray[0][2] = "C";
jArray[0][3] = "D";
//Примеры инициализации массива в одной строк
е
jArray[1] = new string[] {"E", "F", "G"};
jArray[2] = new string[] { "H", "I" };
jArray[3] = new string[4];
jArray[3][0] = "J";
jArray[3][3] = "K";
print ("The Length of jArray is: " + jArray.L
ength);
//Выведет: The Length of jArray is: 4
print ("The Length of jArray[1] is: " + jArra
y [1].Length);
//Выведет: The Length of jArray[1] is: 3
string str = "";
for (int i = 0; i < jArray.Length; i++) {
for (int j = 0; j < jArray [i].Length; j+
+) {
if (jArray [i] [j] != null) {
str += " | " + jArray [i] [j];
} else {
str += " | ";
}
}
str += " | \n";
}
print (str);
}
// Update is called once per frame
void Update () {
}
}
|A|B|C|D|
|E|F|G|
|H|I|
|J| | |K|
Ступенчатые списки
Также возможно создать ступенчатый список List. Ступенчатый
двумерный список строк можно объявить так: List<List<string>>
jaggedStringList. По аналогии со ступенчатыми массивами,
вложенные списки получают значение по умолчанию null, поэтому
их нужно инициализировать при добавлении
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JaggedListTest : MonoBehaviour {
public List<List<string>> jaggedList;
// Используйте этот метод для инициализации
void Start () {
jaggedList = new List<List<string>>();
// Добавить два списка List<string> в jagged
List
jaggedList.Add( new List<string>() );
jaggedList.Add (new List<string> ());
// Добавить две строки в jaggedList[0]
jaggedList[0].Add ("Hello");
jaggedList[0].Add ("World");
// Добавить третий список List<string> в jagg
edList, включая данные
jaggedList.Add ( new List<string>(new string[
] {"complex", "initialization"}) );
string str = "";
foreach (List<string> sL in jaggedList) {
foreach (string sTemp in sL) {
if (sTemp != null) {
str += " | " + sTemp;
} else {
str += " | ";
}
}
str += " | \n";
}
print (str);
}
// Update is called once per frame
void Update () {
}
}
| Hello | World |
| complex | initialization |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JaggedListTest : MonoBehaviour {
public List<List<string>> jaggedList;
// Используйте этот метод для инициализации
void Start () {
jaggedList = new List<List<string>>();
// Добавить два списка List<string> в jagged
List
jaggedList.Add(new List<string>());
jaggedList.Add(new List<string>());
// Добавить две строки в jaggedList[0]
jaggedList[0].Add ("Hello");
jaggedList[0].Add ("World");
// Добавить третий список List<string> в jagg
edList, включая данные
jaggedList.Add ( new List<string>(new string[
] {"complex", "initialization"}) );
string str = "";
for (int i = 0; i < jaggedList.Count; i++) {
for (int j = 0; j < jaggedList[i].Count;
j++) {
if (jaggedList[i][j] != null) {
str += " | " + jaggedList[i][j];
} else {
str += " | ";
}
}
str += " | \n";
}
print (str);
}
// Update is called once per frame
void Update () {
}
}
Этот сценарий выведет:
| Hello | World |
| complex | initialization |
Оператор *=
Умножает значение переменной или свойства на значение
выражения и присваивает результат переменной или
свойству.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeSpawner3 : MonoBehaviour {
public GameObject cubePrefabVar;
public List<GameObject> gameObjectList; //Будет х
ранить все кубики
public float scalingFactor = 0.95f;
// ^ Коэффициент изменения масштаба каждого кубик
а в каждом кадре
public int numCubes = 0; //Общее количество кубик
ов
// Используйте этот метод для инициализации
void Start () {
// Инициализация списка List<GameObject>
gameObjectList = new List<GameObject>();
}
// Update вызывается в каждом кадре
void Update () {
numCubes++; //Увеличить количество кубиков /
/ a
GameObject gObj = Instantiate<GameObject> (cu
bePrefabVar); // b
// Следующие строки устанавливают некоторые з
начения в новом кубике
gObj.name = "Cube " +numCubes; // c
Color c = new Color (Random.value, Random.val
ue, Random.value); // d
gObj.GetComponent<Renderer>().material.color
= c;
// ^ Получить компонент Renderer из gObj и на
значить случайный цвет
gObj.transform.position = Random.insideUnitSp
here; // e
gameObjectList.Add (gObj); //Добавить gObj в
список кубиков
List<GameObject> removeList = new List<GameOb
ject> (); // f
// ^ Список removeList будет хранить кубики,
подлежащие удалению из списка gameObjectList
// Обход кубиков в gameObjectList
foreach (GameObject goTemp in gameObjectList)
{ // g
// Получить масштаб кубика
float scale = goTemp.transform.localScale
.x; // h
scale *= scalingFactor; // Умножить на ко
эффициент scalingFactor
goTemp.transform.localScale = Vector3.one
* scale;
if (scale <= 0.1f) { //Если масштаб меньш
е 0.1f... // i
removeList.Add (goTemp); //...добавит
ь кубик в removeList
}
}
foreach (GameObject goTemp in removeList) { /
/ g
gameObjectList.Remove (goTemp); // j
// ^ Удалить кубик из gameObjectList
Destroy (goTemp); // Удалить игровой объе
кт кубика
}
}
}
Функции и параметры
public class CodeExample : MonoBehaviour {
public int numTimesCalled = 0;
void Update () {
numTimesCalled++;
PrintUpdates();
}
void PrintUpdates() {
string outputMessage = "Updates: " + numTimes
Called;
print (outputMessage); // Пример вывода: "Upd
ates: 1"
}
public class CodeExample : MonoBehaviour {
public int numTimesCalled = 0;
void Update () {
PrintUpdates();
}
void PrintUpdates() {
numTimesCalled++;
print ("Updates: " + numTimesCalled); //Приме
р: "Updates: 5"
}
}
Updates: 1
Updates: 2
Updates: 3
Updates: 4
Updates: 5
…………………
public class CodeExample : MonoBehaviour {
void Awake() {
Say ("Hello"); // 7
}
void Say( string sayThis) { // 10
print (sayThis);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
void Awake() {
PrintGameObjectName(this.gameObject);
SetColor(Color.red, this.gameObject);
}
void PrintGameObjectName( GameObject go ) {
print (go.name);
}
void SetColor(Color c, GameObject go) {
Renderer r = go.GetComponent<Renderer>();
r.material.color = c;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
public GameObject cube;
void Awake() {
GameObject gObj = Instantiate<GameObject> (cu
be);
gObj.name = "CUBE";
PrintGameObjectName(gObj);
SetColor(Color.red, gObj);
}
void PrintGameObjectName( GameObject go ) {
print (go.name);
}
void SetColor(Color c, GameObject go) {
Renderer r = go.GetComponent<Renderer>();
r.material.color = c;
}
}
public class CodeExample : MonoBehaviour {
void Awake() {
int num = Add(2, 5);
print(num);
}
int Add(int numA, int numB) {
int sum = numA + numB;
return(sum);
}
}
Этот сценарий выведет:
public class CodeExample : MonoBehaviour {
public List<GameObject> reallyLongList; // Опреде
ляется в инспекторе // а
void Awake() {
MoveToOrigin("Phil"); //b
}
void MoveToOrigin(string theName) {
foreach (GameObject go in reallyLongList) { /
/c
if (go.name == theName) { //d
go.transform.position = Vector3.zero;
//e
return; //f
}
}
}
Этот сценарий найдёт в списке reallyLongList игровой объект
GameObject с именем "Phil" с помощью цикла foreach и изменит
его местоположение на точку [0,0,0] после чего завершит
выполнение функции MoveToOrigin() и вернет управление в строку
9 при помощи return
public class CodeExample : MonoBehaviour {
void Awake() {
}
void AlignX(GameObject go0, GameObject go1, GameO
bject go2) {
float avgX = go0.transform.position.x;
avgX += go1.transform.position.x;
avgX += go2.transform.position.x;
avgX = avgX / 3.0f;
Vector3 tempPos;
tempPos = go0.transform.position;
tempPos.x = avgX;
go0.transform.position = tempPos;
tempPos = go1.transform.position;
tempPos.x = avgX;
go1.transform.position = tempPos;
tempPos = go2.transform.position;
tempPos.x = avgX;
go2.transform.position = tempPos;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
public GameObject g1;
public GameObject g2;
public GameObject g0;
void Awake() {
AlignX(g0,g1,g2);
}
void AlignX(GameObject go0, GameObject go1, GameO
bject go2) {
float avgX = go0.transform.position.x;
avgX += go1.transform.position.x;
avgX += go2.transform.position.x;
avgX = avgX / 3.0f;
Vector3 tempPos;
tempPos = go0.transform.position;
tempPos.x = avgX;
go0.transform.position = tempPos;
tempPos = go1.transform.position;
tempPos.x = avgX;
go1.transform.position = tempPos;
tempPos = go2.transform.position;
tempPos.x = avgX;
go2.transform.position = tempPos;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
void Awake() {
}
void AlignX(GameObject go0, GameObject go1, GameO
bject go2) {
float avgX = go0.transform.position.x;
avgX += go1.transform.position.x;
avgX += go2.transform.position.x;
avgX = avgX / 3.0f;
SetX(go0, avgX);
SetX(go1, avgX);
SetX(go2, avgX);
}
void SetX( GameObject go, float eX) {
Vector3 tempPos = go.transform.position;
tempPos.x = eX;
go.transform.position = tempPos;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
public GameObject g1;
public GameObject g2;
public GameObject g0;
void Awake() {
AlignX(g0,g1,g2);
}
void AlignX(GameObject go0, GameObject go1, GameO
bject go2) {
float avgX = go0.transform.position.x;
avgX += go1.transform.position.x;
avgX += go2.transform.position.x;
avgX = avgX / 3.0f;
SetX(go0, avgX);
SetX(go1, avgX);
SetX(go2, avgX);
}
void SetX( GameObject go, float eX) {
Vector3 tempPos = go.transform.position;
tempPos.x = eX;
go.transform.position = tempPos;
}
}
Перегрузка функций
Перегрузка функций — причудливый термин, описывающий
возможность функций в C# действовать по-разному в зависимости
от типов и количества передаваемых им параметров. В следующем
листинге жирным выделены фрагменты, демонстрирующие
перегрузку функций.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
void Awake() {
print( Add(1.0f, 2.5f));
// ^ Выведет: "3.5"
print( Add( new Vector3(1, 0, 0), new Vector3
(0, 1, 0)));
// ^ Выведет "(1.0, 1.0, 0.0)"
Color colorA = new Color(0.5f, 1, 0, 1);
Color colorB = new Color(0.25f, 0.33f, 0, 1);
print( Add(colorA, colorB ));
// ^ Выведет "RGBA(0.750, 1.000, 0.000, 1.000
)"
}
float Add( float f0, float f1 ) { // a
return(f0 + f1);
}
Vector3 Add( Vector3 v0, Vector3 v1 ) { // a
return(v0 + v1);
}
Color Add( Color c0, Color c1 ) { // a
float r, g, b, a;
r = Mathf.Min(c0.r + c1.r, 1.0f); // b
g = Mathf.Min(c0.g + c1.g, 1.0f); // b
b = Mathf.Min(c0.b + c1.b, 1.0f); // b
a = Mathf.Min(c0.a + c1.a, 1.0f); // b
return(new Color(r, g, b, a));
}
}
3.5
Необязательные параметры
Иногда желательно, чтобы функция имела необязательные
параметры, которые могут передаваться или не передаваться. В
следующем листинге параметр еХ функции SetX( ) является
необязательным. Если задать значение по умолчанию для
параметра в определении функции, компилятор будет
интерпретировать его как необязательный (как, например, в строке
13 в следующем листинге, где параметр еХ получает значение по
умолчанию 0,0f).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
void Awake() {
SetX(this.gameObject, 25 ); // b
print(this.gameObject.transform.position.x );
// Выведет: "25"
SetX( this.gameObject ); // c
print(this.gameObject.transform.position.x );
//Выведет: "0"
}
void SetX( GameObject go, float eX = 0.0f ) { //
a
Vector3 tempPos = go.transform.position;
tempPos.x = eX;
go.transform.position = tempPos;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
public GameObject gObj;
void Awake() {
SetX(gObj, 25 ); // b
print(gObj.transform.position.x ); // Выведет
: "25"
SetX( gObj ); // c
print(gObj.transform.position.x ); //Выведет:
"0"
}
void SetX( GameObject go, float eX = 0.0f ) { //
a
Vector3 tempPos = go.transform.position;
tempPos.x = eX;
go.transform.position = tempPos;
}
}
25
public class CodeExample : MonoBehaviour {
void Awake() {
print(Add(1)); // Выведет: "1"
print(Add(1,2)); // Выведет: "3"
print(Add(1,2,3)); // Выведет: "6"
print(Add(1,2,3,4)); // Выведет: "10"
}
int Add( params int[] ints ) {
int sum = 0;
foreach (int i in ints) {
sum += i;
}
return(sum);
}
}
10
Теперь функция Add() может принимать любое количество целых
чисел и возвращать их сумму Подобно необязательным
параметрам, список params должен следовать в объявлении
функции после всех обязательных параметров (то есть все
обязательные параметры должны быть объявлены перед списком
params).
public class CodeExample : MonoBehaviour {
void AlignX( params GameObject[] goArray ) { //a
float sumX = 0;
foreach(GameObject go in goArray) {
sumX += go.transform.position.x;
}
float avgX = sumX / goArray.Length;
foreach (GameObject go in goArray) {
SetX (go, avgX);
}
}
void SetX( GameObject go, float eX ) {
Vector3 tempPos = go.transform.position;
tempPos.x = eX;
go.transform.position = tempPos;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CodeExample : MonoBehaviour {
public GameObject gObj;
public GameObject gObj1;
public GameObject gObj2;
void Start() {
AlignX(gObj, gObj1, gObj2);
}
void AlignX( params GameObject[] goArray ) {
float sumX = 0;
foreach(GameObject go in goArray) {
sumX += go.transform.position.x;
}
float avgX = sumX / goArray.Length;
foreach (GameObject go in goArray) {
SetX (go, avgX);
}
}
void SetX( GameObject go, float eX ) {
Vector3 tempPos = go.transform.position;
tempPos.x = eX;
go.transform.position = tempPos;
}
}
public class CodeExample : MonoBehaviour {
void Awake() {
print(Fac(5)); // Выведет: "120" // a
print(Fac(0)); // Выведет: "1"
print(Fac(-5)); // Выведет: "0"
}
int Fac( int n ) { // b, d
if (n < 0) { //Обрабатывает случай if n<0
return(0);
}
if (n == 0) { // Это "завершающий случай" //
e
return(1);
}
int result = n * Fac(n-1); // c, f
return(result); // g
}
}
Этот сценарий выведет:
120
1
0
Отладка
Ошибки времени компиляции
Ошибка времени компиляции — это проблема, которую Unity
обнаруживает во время компиляции кода на C# (то есть при
попытке интерпретировать код на C# и превратить его в код на
обобщенном промежуточном языке (Common Intermediate
Language), который позднее будет преобразован средой Unity в
машинный код, понятный компьютеру).