Примеры кода
Пример 1: Работа с GameObject
Основы создания и управления игровыми объектами в Unity:
using UnityEngine;
public class GameObjectExample : MonoBehaviour
{
public GameObject prefabToSpawn;
public Transform spawnPoint;
private GameObject spawnedObject;
void Start()
{
CreateNewObject();
FindObjectsOnScene();
}
void CreateNewObject()
{
if (prefabToSpawn != null && spawnPoint != null)
{
spawnedObject = Instantiate(prefabToSpawn, spawnPoint.position, spawnPoint.rotation);
spawnedObject.name = "Созданный объект";
Debug.Log("Объект создан: " + spawnedObject.name);
}
}
void FindObjectsOnScene()
{
GameObject player = GameObject.Find("Player");
if (player != null)
{
Debug.Log("Найден игрок: " + player.name);
}
GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("Enemy");
Debug.Log("Найдено врагов: " + allEnemies.Length);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && spawnedObject != null)
{
Destroy(spawnedObject);
Debug.Log("Объект удален");
}
}
}
Пример 2: Работа с компонентами
Получение и управление компонентами GameObject:
using UnityEngine;
public class ComponentExample : MonoBehaviour
{
private Rigidbody rb;
private Renderer objectRenderer;
private Collider objectCollider;
void Start()
{
GetRequiredComponents();
SetupComponents();
}
void GetRequiredComponents()
{
rb = GetComponent<Rigidbody>();
if (rb == null)
{
rb = gameObject.AddComponent<Rigidbody>();
Debug.Log("Rigidbody добавлен автоматически");
}
objectRenderer = GetComponent<Renderer>();
objectCollider = GetComponent<Collider>();
}
void SetupComponents()
{
if (rb != null)
{
rb.mass = 1f;
rb.drag = 0.5f;
rb.useGravity = true;
}
if (objectRenderer != null)
{
objectRenderer.material.color = Color.blue;
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.G) && rb != null)
{
rb.useGravity = !rb.useGravity;
Debug.Log("Гравитация: " + rb.useGravity);
}
}
}
Пример 3: Система движения
Различные способы перемещения объектов в Unity:
using UnityEngine;
public class MovementExample : MonoBehaviour
{
public float moveSpeed = 5f;
public float rotationSpeed = 100f;
public float jumpForce = 10f;
private Rigidbody rb;
private bool isGrounded = true;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
HandleMovement();
HandleRotation();
HandleJump();
}
void HandleMovement()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;
transform.Translate(direction * moveSpeed * Time.deltaTime);
}
void HandleRotation()
{
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(0, -rotationSpeed * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.E))
{
transform.Rotate(0, rotationSpeed * Time.deltaTime, 0);
}
}
void HandleJump()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded && rb != null)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isGrounded = false;
Debug.Log("Прыжок!");
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
Пример 4: Система ввода
Обработка пользовательского ввода в Unity:
using UnityEngine;
public class InputExample : MonoBehaviour
{
public float mouseSensitivity = 2f;
public KeyCode actionKey = KeyCode.F;
private Camera playerCamera;
private float xRotation = 0f;
void Start()
{
playerCamera = Camera.main;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
HandleKeyboardInput();
HandleMouseInput();
}
void HandleKeyboardInput()
{
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("Нажата клавиша W");
}
if (Input.GetKeyDown(actionKey))
{
PerformAction();
}
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
if (horizontal != 0 || vertical != 0)
{
Debug.Log($"Движение: X={horizontal:F2}, Y={vertical:F2}");
}
}
void HandleMouseInput()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
if (playerCamera != null)
{
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
transform.Rotate(Vector3.up * mouseX);
}
}
void PerformAction()
{
Debug.Log("Выполнено действие!");
RaycastHit hit;
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, 5f))
{
Debug.Log("Взаимодействие с: " + hit.collider.name);
}
}
}
Пример 5: Система коллизий
Обработка столкновений и триггеров в Unity:
using UnityEngine;
public class CollisionExample : MonoBehaviour
{
public int health = 100;
public float damageAmount = 10f;
public GameObject explosionEffect;
void OnCollisionEnter(Collision collision)
{
Debug.Log("Столкновение с: " + collision.gameObject.name);
if (collision.gameObject.CompareTag("Enemy"))
{
TakeDamage(damageAmount);
}
if (collision.gameObject.CompareTag("Ground"))
{
Debug.Log("Приземление");
}
}
void OnTriggerEnter(Collider other)
{
Debug.Log("Вход в триггер: " + other.name);
if (other.CompareTag("Collectible"))
{
CollectItem(other.gameObject);
}
if (other.CompareTag("DeathZone"))
{
Die();
}
}
void TakeDamage(float damage)
{
health -= Mathf.RoundToInt(damage);
Debug.Log($"Получен урон: {damage}. Здоровье: {health}");
if (health <= 0)
{
Die();
}
}
void CollectItem(GameObject item)
{
Debug.Log("Собран предмет: " + item.name);
if (explosionEffect != null)
{
Instantiate(explosionEffect, item.transform.position, Quaternion.identity);
}
Destroy(item);
}
void Die()
{
Debug.Log("Игрок погиб!");
if (explosionEffect != null)
{
Instantiate(explosionEffect, transform.position, Quaternion.identity);
}
gameObject.SetActive(false);
}
}