Примеры кода
Пример 1: Переменные и типы данных
Основные типы данных и работа с переменными в C#:
using UnityEngine;
public class VariablesExample : MonoBehaviour
{
// Числовые типы
public int playerHealth = 100;
public float moveSpeed = 5.5f;
public double preciseValue = 3.14159;
// Текст и логика
public string playerName = "Игрок";
public bool isAlive = true;
public char grade = 'A';
// Unity типы
public Vector3 position;
public Color playerColor = Color.red;
void Start()
{
ShowVariableTypes();
PerformCalculations();
}
void ShowVariableTypes()
{
Debug.Log("Здоровье (int): " + playerHealth);
Debug.Log("Скорость (float): " + moveSpeed);
Debug.Log("Имя (string): " + playerName);
Debug.Log("Жив (bool): " + isAlive);
}
void PerformCalculations()
{
int damage = 25;
int newHealth = playerHealth - damage;
Debug.Log($"Здоровье после урона: {newHealth}");
float distance = moveSpeed * Time.deltaTime;
Debug.Log($"Расстояние за кадр: {distance}");
bool isHealthLow = playerHealth < 30;
Debug.Log($"Мало здоровья? {isHealthLow}");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.H))
{
playerHealth -= 10;
Debug.Log("Урон! Здоровье: " + playerHealth);
}
}
}
Пример 2: Функции и методы
Создание и использование функций в C#:
using UnityEngine;
public class FunctionsExample : MonoBehaviour
{
private int currentHealth = 100;
private int experience = 0;
void Start()
{
InitializePlayer();
ShowPlayerInfo();
}
// Функция без параметров
void InitializePlayer()
{
currentHealth = 100;
experience = 0;
Debug.Log("Игрок инициализирован");
}
// Функция с параметрами
void TakeDamage(int damage)
{
currentHealth -= damage;
currentHealth = Mathf.Max(0, currentHealth);
Debug.Log($"Урон: {damage}. Здоровье: {currentHealth}");
}
// Функция с возвращаемым значением
bool IsAlive()
{
return currentHealth > 0;
}
// Функция с несколькими параметрами
float CalculateDamage(float baseDamage, float multiplier)
{
return baseDamage * multiplier;
}
// Функция с параметром по умолчанию
void Heal(int healAmount = 20)
{
currentHealth += healAmount;
Debug.Log($"Лечение: {healAmount}. Здоровье: {currentHealth}");
}
public void ShowPlayerInfo()
{
Debug.Log($"Здоровье: {currentHealth}");
Debug.Log($"Опыт: {experience}");
Debug.Log($"Жив: {IsAlive()}");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
float damage = CalculateDamage(20f, 1.5f);
TakeDamage(Mathf.RoundToInt(damage));
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
Heal();
}
}
}
Пример 3: Классы и объекты
Создание и использование классов в C#:
using UnityEngine;
// Базовый класс персонажа
public class Character
{
protected string characterName;
protected int health;
protected int maxHealth;
public string Name { get { return characterName; } }
public int Health { get { return health; } }
public bool IsAlive => health > 0;
public Character(string name, int maxHp)
{
characterName = name;
maxHealth = maxHp;
health = maxHealth;
}
public virtual void TakeDamage(int damage)
{
health -= damage;
health = Mathf.Max(0, health);
Debug.Log($"{characterName} получил {damage} урона");
}
}
// Класс игрока
public class Player : Character
{
private int experience;
public Player(string name) : base(name, 100)
{
experience = 0;
}
public override void TakeDamage(int damage)
{
int reducedDamage = Mathf.Max(1, damage - 5);
base.TakeDamage(reducedDamage);
Debug.Log("Броня поглотила урон!");
}
public void AddExperience(int exp)
{
experience += exp;
Debug.Log($"Получен опыт: {exp}");
}
}
// Класс врага
public class Enemy : Character
{
private int attackPower;
public Enemy(string name, int hp, int attack) : base(name, hp)
{
attackPower = attack;
}
public void Attack(Character target)
{
Debug.Log($"{characterName} атакует!");
target.TakeDamage(attackPower);
}
}
public class ClassesExample : MonoBehaviour
{
private Player player;
private Enemy enemy;
void Start()
{
player = new Player("Герой");
enemy = new Enemy("Гоблин", 50, 15);
Debug.Log("Персонажи созданы!");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
player.TakeDamage(10);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
enemy.Attack(player);
}
}
}
Пример 4: Массивы и списки
Работа с массивами и коллекциями в C#:
using UnityEngine;
using System.Collections.Generic;
public class ArraysExample : MonoBehaviour
{
// Массивы
public string[] playerNames = {"Алексей", "Мария", "Иван"};
public int[] scores = {100, 250, 180};
// Списки
public List<string> inventory = new List<string>();
void Start()
{
DemonstrateArrays();
DemonstrateLists();
}
void DemonstrateArrays()
{
Debug.Log("=== Массивы ===");
// Создание массива
int[] numbers = new int[5];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = i * 10;
}
// Вывод массива
foreach (int number in numbers)
{
Debug.Log("Число: " + number);
}
// Работа с именами и очками
for (int i = 0; i < playerNames.Length; i++)
{
Debug.Log($"{playerNames[i]} - {scores[i]} очков");
}
}
void DemonstrateLists()
{
Debug.Log("=== Списки ===");
// Добавление элементов
inventory.Add("Меч");
inventory.Add("Щит");
inventory.Add("Зелье");
// Вывод списка
for (int i = 0; i < inventory.Count; i++)
{
Debug.Log($"{i + 1}. {inventory[i]}");
}
// Поиск и удаление
bool hasSword = inventory.Contains("Меч");
Debug.Log("Есть меч: " + hasSword);
inventory.Remove("Зелье");
Debug.Log("Зелье использовано");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
string[] items = {"Кольцо", "Амулет", "Свиток"};
string randomItem = items[Random.Range(0, items.Length)];
inventory.Add(randomItem);
Debug.Log("Найден: " + randomItem);
}
}
}
Пример 5: Условные операторы
Использование условий и циклов в C#:
using UnityEngine;
public class ConditionsExample : MonoBehaviour
{
public int playerLevel = 1;
public int playerHealth = 100;
public string playerClass = "Воин";
void Start()
{
DemonstrateConditions();
DemonstrateLoops();
}
void DemonstrateConditions()
{
Debug.Log("=== Условия ===");
// Простое условие if
if (playerHealth > 50)
{
Debug.Log("Здоровье в норме");
}
// if-else
if (playerLevel >= 10)
{
Debug.Log("Опытный игрок");
}
else
{
Debug.Log("Новичок");
}
// if-else if-else
if (playerHealth > 80)
{
Debug.Log("Отличное здоровье");
}
else if (playerHealth > 50)
{
Debug.Log("Хорошее здоровье");
}
else if (playerHealth > 20)
{
Debug.Log("Низкое здоровье");
}
else
{
Debug.Log("Критическое состояние!");
}
// switch
switch (playerClass)
{
case "Воин":
Debug.Log("Сильный в ближнем бою");
break;
case "Маг":
Debug.Log("Владеет магией");
break;
case "Лучник":
Debug.Log("Мастер дальнего боя");
break;
default:
Debug.Log("Неизвестный класс");
break;
}
}
void DemonstrateLoops()
{
Debug.Log("=== Циклы ===");
// Цикл for
Debug.Log("Цикл for:");
for (int i = 1; i <= 5; i++)
{
Debug.Log("Итерация: " + i);
}
// Цикл while
Debug.Log("Цикл while:");
int count = 0;
while (count < 3)
{
Debug.Log("Count: " + count);
count++;
}
// Цикл foreach с массивом
string[] weapons = {"Меч", "Лук", "Посох"};
Debug.Log("Оружие:");
foreach (string weapon in weapons)
{
Debug.Log("- " + weapon);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
playerHealth -= 20;
CheckHealthStatus();
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
playerLevel++;
CheckLevelRewards();
}
}
void CheckHealthStatus()
{
if (playerHealth <= 0)
{
Debug.Log("Игрок погиб!");
}
else if (playerHealth < 30)
{
Debug.Log("Нужно лечение!");
}
}
void CheckLevelRewards()
{
if (playerLevel % 5 == 0)
{
Debug.Log("Получена награда за уровень!");
}
}
}