Unidad Cheatsheet¶
¶
¶
▪h1 - Desarrollo del juego para móvil "Clase de inscripción" Unity es un potente motor de juego multiplataforma utilizado para crear juegos y simulaciones 2D, 3D, VR y AR. Esta hoja de trampa se centra en el desarrollo del juego móvil con Unity. ▪/p] ■/div titulada
¶
########################################################################################################################################################################################################################################################## Copiar todos los comandos¶
########################################################################################################################################################################################################################################################## Generar PDF seleccionado/button¶
■/div titulada ■/div titulada
Cuadro de contenidos¶
- Instalación
- Unity Editor
- Core Concepts
- Scripting with C#
- Physics
- UI System
- Animación
- Mobile Development
- Perfeccionamiento Optimización
- Asset Management
- Testing " Debugging
- Deployment
- Las mejores prácticas
Instalación¶
Unity Hub¶
# Download Unity Hub from unity.com
# Unity Hub manages Unity versions and projects
# Install Unity version
# Open Unity Hub -> Installs -> Add
# Select desired Unity version (e.g., 2021.3 LTS)
# Add modules: Android Build Support, iOS Build Support
# Set environment variables (optional)
# UNITY_HOME=/path/to/unity/version
# PATH=$PATH:$UNITY_HOME/Editor
Android Setup¶
# In Unity Hub, add Android Build Support module
# Unity will install required Android SDK & NDK
# Verify setup in Unity Editor
# Edit -> Preferences -> External Tools
# Check Android SDK, NDK, and JDK paths
# For custom SDK/NDK
# Download from developer.android.com
# Set paths in Unity Editor
iOS Setup (sólo MacOS)¶
# In Unity Hub, add iOS Build Support module
# Install Xcode from Mac App Store
# Install Xcode Command Line Tools
xcode-select --install
# Install CocoaPods
sudo gem install cocoapods
# Verify setup in Unity Editor
# Edit -> Preferences -> External Tools
# Check Xcode path
Unity Editor¶
Windows principal¶
- Scene View: Representación visual del mundo del juego
- Vista del juego: Vista previa del juego visto por el jugador
- ** Jerarquía**: Lista de todos los objetos del juego en la escena actual
- Proyecto: Navegador para todos los activos del proyecto
- Inspector: Propiedades del Juego seleccionadoObjeto o activo
- Consola: Muestra registros, advertencias y errores
Atajos de teclado¶
- Q: Herramienta de mano (pan)
- **W **: Move Tool
- E: Herramienta rotatoria
- R: Herramienta de escala
- T: Rect Tool (para UI)
- Ctrl/Cmd + S: Guardar escena
- Ctrl/Cmd + P: Juego/Pausa Juego
- Ctrl/Cmd + cambio + P: Marco de paso
- F: Centrarse en el objeto seleccionado
- Ctrl/Cmd + D: Duplicar objeto seleccionado
Project Management¶
# Create new project
# Unity Hub -> Projects -> New
# Select template (2D, 3D, URP, HDRP)
# Enter project name and location
# Open existing project
# Unity Hub -> Projects -> Add
# Select project folder
# Upgrade project
# Open project in newer Unity version
# Unity will prompt for upgrade
Conceptos básicos¶
GameObject¶
- Los objetos fundamentales en la unidad que representan personajes, props, paisajes, cámaras, etc.
- Un contenedor para componentes.
Componente¶
- Piezas funcionales de un objeto de juego.
- Ejemplos: Transform, Mesh Renderer, Rigidbody, Collider, Scripts.
Componente de transformación¶
- Cada GameObject tiene un componente Transform.
- Define la posición, rotación y escala del GameObject.
Escena¶
- Un contenedor para un conjunto de objetos del juego.
- Representa un nivel, un menú o una parte del juego.
Prefab¶
- Un objeto reutilizable almacenado en la vista del proyecto.
- Permite crear, configurar y almacenar un GameObject completo con todos sus componentes, valores de propiedad y objetos infantiles como activo reutilizable.
Activo¶
- Cualquier archivo utilizado en un proyecto Unity, como modelos, texturas, sonidos, scripts, etc.
Guión con C¶
Crear un script¶
// In Project view, right-click -> Create -> C# Script
// Name the script (e.g., PlayerController)
// Attach script to a GameObject by dragging it to the Inspector
MonoBehaviour Ciclo de vida¶
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Called when the script instance is being loaded
void Awake()
{
Debug.Log("Awake called");
}
// Called on the frame when a script is enabled before any of the Update methods are called the first time
void Start()
{
Debug.Log("Start called");
}
// Called every frame
void Update()
{
// Game logic that needs to run every frame
}
// Called every fixed framerate frame
void FixedUpdate()
{
// Physics calculations
}
// Called every frame, after all Update functions have been called
void LateUpdate()
{
// Camera movement, etc.
}
// Called when the object becomes enabled and active
void OnEnable()
{
Debug.Log("OnEnable called");
}
// Called when the object becomes disabled or inactive
void OnDisable()
{
Debug.Log("OnDisable called");
}
// Called when the MonoBehaviour will be destroyed
void OnDestroy()
{
Debug.Log("OnDestroy called");
}
}
Accessing Components¶
// Get component on the same GameObject
Rigidbody rb = GetComponent<Rigidbody>();
// Get component on a child GameObject
Transform childTransform = GetComponentInChildren<Transform>();
// Get component on a parent GameObject
PlayerController parentController = GetComponentInParent<PlayerController>();
// Add component to GameObject
BoxCollider collider = gameObject.AddComponent<BoxCollider>();
// Find GameObject by name
GameObject player = GameObject.Find("Player");
// Find GameObject by tag
GameObject enemy = GameObject.FindWithTag("Enemy");
// Find all GameObjects with tag
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
Manejo de entrada¶
// Keyboard input
if (Input.GetKeyDown(KeyCode.Space))
{
// Jump
}
if (Input.GetKey(KeyCode.A))
{
// Move left
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
// Stop sprinting
}
// Mouse input
if (Input.GetMouseButtonDown(0))
{
// Left mouse button clicked
}
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
// Touch input
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
Debug.Log("Touch began");
}
if (touch.phase == TouchPhase.Moved)
{
Debug.Log("Touch moved");
}
if (touch.phase == TouchPhase.Ended)
{
Debug.Log("Touch ended");
}
}
Coroutines¶
using System.Collections;
using UnityEngine;
public class CoroutineExample : MonoBehaviour
{
void Start()
{
StartCoroutine(Fade());
}
IEnumerator Fade()
{
Debug.Log("Coroutine started");
// Wait for 2 seconds
yield return new WaitForSeconds(2f);
Debug.Log("After 2 seconds");
// Wait for the end of the frame
yield return new WaitForEndOfFrame();
Debug.Log("End of frame");
// Wait for another coroutine to finish
yield return StartCoroutine(AnotherCoroutine());
Debug.Log("Coroutine finished");
}
IEnumerator AnotherCoroutine()
{
Debug.Log("Another coroutine started");
yield return new WaitForSeconds(1f);
Debug.Log("Another coroutine finished");
}
// Stop a coroutine
public void StopMyCoroutine()
{
StopCoroutine(Fade());
StopAllCoroutines();
}
}
Scene Management¶
using UnityEngine.SceneManagement;
// Load a scene by name
SceneManager.LoadScene("Level1");
// Load a scene by index
SceneManager.LoadScene(1);
// Load a scene asynchronously
StartCoroutine(LoadSceneAsync("Level2"));
IEnumerator LoadSceneAsync(string sceneName)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
while (!asyncLoad.isDone)
{
float progress = Mathf.Clamp01(asyncLoad.progress / 0.9f);
Debug.Log("Loading progress: " + (progress * 100) + "%");
yield return null;
}
}
// Get the current scene
Scene currentScene = SceneManager.GetActiveScene();
string sceneName = currentScene.name;
Física¶
Rigidbody¶
- Componente que permite que un GameObject sea afectado por la física.
- Para la física 3D.
- Para la física 2D.
// Get Rigidbody component
Rigidbody rb = GetComponent<Rigidbody>();
// Add force
rb.AddForce(Vector3.forward * 10f, ForceMode.Impulse);
// Add torque (rotation)
rb.AddTorque(Vector3.up * 5f, ForceMode.Force);
// Set velocity
rb.velocity = new Vector3(0, 10, 0);
// Move position (for kinematic rigidbodies)
rb.MovePosition(transform.position + Vector3.forward * Time.deltaTime);
// Move rotation
rb.MoveRotation(transform.rotation * Quaternion.Euler(Vector3.up * 10f * Time.deltaTime));
Collider¶
- Define la forma de un GameObject para colisiones físicas.
- BoxCollider, SphereCollider, CapsuleCollider, MeshCollider.
-
BoxCollider 2D**, CircleCollider2D, CapsuleCollider2D.¶
Detección de colisión¶
// Called when this collider/rigidbody has begun touching another rigidbody/collider
void OnCollisionEnter(Collision collision)
{
Debug.Log("Collision entered with: " + collision.gameObject.name);
if (collision.gameObject.CompareTag("Enemy"))
{
// Take damage
}
}
// Called once per frame for every collider/rigidbody that is touching another rigidbody/collider
void OnCollisionStay(Collision collision)
{
Debug.Log("Collision staying with: " + collision.gameObject.name);
}
// Called when this collider/rigidbody has stopped touching another rigidbody/collider
void OnCollisionExit(Collision collision)
{
Debug.Log("Collision exited with: " + collision.gameObject.name);
}
Detección de desencadenantes¶
- Los colgadores pueden ser marcados como "Es Trigger" para detectar cuando los objetos entran en su volumen sin causar una colisión.
// Called when the Collider other enters the trigger
void OnTriggerEnter(Collider other)
{
Debug.Log("Trigger entered by: " + other.gameObject.name);
if (other.CompareTag("Player"))
{
// Collect item
}
}
// Called once per frame for every Collider other that is touching the trigger
void OnTriggerStay(Collider other)
{
Debug.Log("Trigger staying with: " + other.gameObject.name);
}
// Called when the Collider other has stopped touching the trigger
void OnTriggerExit(Collider other)
{
Debug.Log("Trigger exited by: " + other.gameObject.name);
}
Raycasting¶
// Cast a ray from the camera to the mouse position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100f))
{
Debug.Log("Ray hit: " + hit.collider.gameObject.name);
Debug.Log("Hit point: " + hit.point);
}
// Cast a ray from a transform
if (Physics.Raycast(transform.position, transform.forward, out hit, 10f))
{
Debug.Log("Forward ray hit: " + hit.collider.gameObject.name);
}
// Raycast with layer mask
int layerMask = 1 << 8; // Layer 8
if (Physics.Raycast(transform.position, Vector3.down, out hit, 2f, layerMask))
{
Debug.Log("Ground detected");
}
Sistema UI¶
Canvas¶
- El elemento raíz de toda la UI en una escena.
- Modo de Render: Espacio de Pantalla - Superposición, Espacio de Pantalla - Cámara, Espacio Mundial.
UI Components¶
- Texto: Muestra texto.
- Imagen: Muestra una imagen.
- RawImage: Muestra una textura.
- Button: Un botón clicable.
- Una casilla.
- Un deslizador arrastrable.
- Una barra de desplazamiento.
- InputField: Un campo de entrada de texto.
- Panel: Un contenedor para otros elementos de la UI.
-
Scroll Vista**: Una vista desplazable.¶
Rect Transform¶
- El componente Transform para elementos UI.
- Define posición, tamaño, anclas y pivote.
Sistema de eventos¶
- Maneja eventos de entrada para elementos UI.
- Requiere un EventSystem JuegoObjeto en la escena.
Botón Haga clic en el evento¶
using UnityEngine.UI;
public Button myButton;
void Start()
{
myButton.onClick.AddListener(OnButtonClick);
}
void OnButtonClick()
{
Debug.Log("Button clicked!");
}
Accessing UI Components¶
using UnityEngine.UI;
public Text scoreText;
public Image healthBar;
public InputField nameInput;
void UpdateScore(int score)
{
scoreText.text = "Score: " + score;
}
void UpdateHealth(float health)
{
healthBar.fillAmount = health / 100f;
}
string GetPlayerName()
{
return nameInput.text;
}
Animación¶
Componente de imagen¶
- Controla las animaciones en un GameObject.
- Utiliza un activo Animator Controller para administrar estados de animación.
Controlador de imágenes¶
- Una máquina estatal para animaciones.
- Estados: Representar animaciones individuales (por ejemplo, Idle, Walk, Run, Jump).
- Transiciones: Defina cómo moverse entre estados.
- ** Parámetros**: Variables que controlan las transiciones (por ejemplo, Velocidad, IsJumping).
Clips de animación¶
- Activos que contienen datos de animación (por ejemplo, claves para la posición, rotación, escala).
Animaciones de control de script¶
Animator animator = GetComponent<Animator>();
// Set float parameter
animator.SetFloat("Speed", moveSpeed);
// Set bool parameter
animator.SetBool("IsJumping", true);
// Set trigger parameter
animator.SetTrigger("Attack");
// Get current animation state
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
if (stateInfo.IsName("Attack"))
{
// In attack animation
}
Animación Eventos¶
- Llame una función en un punto específico en un clip de animación.
- Añade un evento en la ventana Animation.
// Function to be called by animation event
public void OnAttackAnimationEnd()
{
Debug.Log("Attack animation finished");
}
Mobile Development¶
Recopilación de plataformas¶
#if UNITY_ANDROID
// Android-specific code
#elif UNITY_IOS
// iOS-specific code
#else
// Code for other platforms (e.g., Editor)
#endif
Orientación de pantalla¶
// Set screen orientation
Screen.orientation = ScreenOrientation.LandscapeLeft;
// Allow auto-rotation
Screen.autorotateToPortrait = true;
Screen.autorotateToLandscapeLeft = true;
Screen.autorotateToLandscapeRight = true;
Screen.autorotateToPortraitUpsideDown = false;
Controles táctiles¶
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
case TouchPhase.Began:
// Handle touch began
break;
case TouchPhase.Moved:
// Handle touch moved
Vector2 touchDeltaPosition = touch.deltaPosition;
break;
case TouchPhase.Ended:
// Handle touch ended
break;
}
}
}
Accelerometer¶
// Get accelerometer data
Vector3 acceleration = Input.acceleration;
// Use accelerometer for movement
float moveHorizontal = acceleration.x;
float moveVertical = acceleration.y;
Gyroscope¶
// Enable gyroscope
Input.gyro.enabled = true;
// Get gyroscope data
Quaternion rotation = Input.gyro.attitude;
Vector3 rotationRate = Input.gyro.rotationRate;
Vibración de dispositivo¶
Datos persistentes¶
// PlayerPrefs for simple data storage
PlayerPrefs.SetInt("HighScore", 100);
PlayerPrefs.SetString("PlayerName", "John");
PlayerPrefs.SetFloat("Volume", 0.8f);
int highScore = PlayerPrefs.GetInt("HighScore", 0);
string playerName = PlayerPrefs.GetString("PlayerName", "Guest");
float volume = PlayerPrefs.GetFloat("Volume", 1.0f);
PlayerPrefs.Save();
// For complex data, use file I/O
string path = Application.persistentDataPath + "/save.dat";
File.WriteAllText(path, "My save data");
string saveData = File.ReadAllText(path);
Optimización del rendimiento¶
Profiler¶
- Una herramienta para analizar y optimizar el rendimiento del juego.
- Window - título Análisis - confianza Perfilador.
- CPU Uso: Identificar los cuellos de botella de rendimiento en scripts.
- Uso de GPU: Analizar el rendimiento de renderizado.
- ** Memoria**: Seguimiento de asignaciones de memoria e identificación de fugas de memoria.
Batching¶
- Static Batching: Para objetos que no se mueven que comparten el mismo material.
- Dinamic Batching: Para pequeños objetos móviles que comparten el mismo material.
Cultivos¶
- Frustum Culling: Activado automáticamente. Los objetos fuera de la vista de la cámara no se muestran.
- Oclusión Culling: Evita la entrega de objetos que están ocultos detrás de otros objetos.
Nivel de detalle (LOD)¶
- Presenta modelos con diferentes niveles de detalle basados en su distancia de la cámara.
Compresión de la textura¶
- Utilice formatos de compresión de textura adecuados para cada plataforma (por ejemplo, ASTC para Android/iOS).
Objeto¶
- Reutilizar objetos en lugar de instantáneas y destruirlos con frecuencia.
public class ObjectPool : MonoBehaviour
{
public GameObject objectToPool;
public int amountToPool;
private List<GameObject> pooledObjects;
void Start()
{
pooledObjects = new List<GameObject>();
for (int i = 0; i < amountToPool; i++)
{
GameObject obj = Instantiate(objectToPool);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
return null;
}
}
Gestión de activos¶
AssetBundles¶
- Archivos de activos que se pueden cargar bajo demanda.
- Se utiliza para el contenido descargable (DLC) y reducir el tamaño de la aplicación inicial.
Activos abordables¶
- Un sistema para gestionar y cargar activos por dirección.
- Simplifica la gestión y carga de activos.
Resources Folder¶
- Una carpeta especial donde los activos pueden ser cargados por nombre en tiempo de ejecución.
- No se recomienda para grandes proyectos debido a las implicaciones en el desempeño.
// Load asset from Resources folder
Texture2D texture = Resources.Load<Texture2D>("Textures/my_texture");
GameObject prefab = Resources.Load<GameObject>("Prefabs/my_prefab");
Pruebas " Debugging "¶
Debugging¶
// Log messages to the console
Debug.Log("This is a log message");
Debug.LogWarning("This is a warning");
Debug.LogError("This is an error");
// Draw debug lines in the Scene view
Debug.DrawLine(transform.position, transform.position + transform.forward * 10f, Color.red);
Debug.DrawRay(transform.position, transform.forward * 10f, Color.green);
// Assertions
Debug.Assert(condition, "Assertion failed");
Marco de prueba de unidad¶
- Un marco para escribir y realizar pruebas automatizadas en Unity.
- Window - título General - título Test Runner.
- Edit Mode Tests: Corre en el Editor de Unidad.
- ** Pruebas del modo de juego**: Correr en el juego mientras está jugando.
// Edit Mode Test
using NUnit.Framework;
public class CalculatorTests
{
[Test]
public void Add_TwoNumbers_ReturnsSum()
{
var calculator = new Calculator();
var result = calculator.Add(2, 3);
Assert.AreEqual(5, result);
}
}
// Play Mode Test
using System.Collections;
using NUnit.Framework;
using UnityEngine.TestTools;
public class PlayerTests
{
[UnityTest]
public IEnumerator Player_Jumps_ChangesYPosition()
{
var player = new GameObject().AddComponent<Player>();
float initialY = player.transform.position.y;
player.Jump();
yield return new WaitForSeconds(0.5f);
Assert.Greater(player.transform.position.y, initialY);
}
}
Despliegue¶
Configuración de construcción¶
- File - título Configuración de construcción.
- Select target platform (Android, iOS).
- Añadir escenas al edificio.
- Configuración de reproductores.
Ajustes del reproductor¶
- Editar - titulado Configuración del proyecto - Jugador.
- ** Nombre de la compañía**, ** Nombre del producto**, Versión.
- Icon, Splash Screen.
- Bundle Identifier (por ejemplo, com.company.product).
- Scripting Backend (Mono, IL2CPP).
- API Compatibilidad Nivel.
Android Build¶
# In Build Settings, switch to Android platform
# Connect Android device with USB debugging enabled
# Click "Build and Run"
# To create an APK
# Click "Build"
# Save the APK file
# To create an AAB (Android App Bundle)
# Check "Build App Bundle (Google Play)"
# Click "Build"
iOS Build (sólo MacOS)¶
# In Build Settings, switch to iOS platform
# Click "Build"
# This will generate an Xcode project
# Open the Xcode project
# In Xcode, set up signing and capabilities
# Select target device and run the app
# To create an archive for App Store
# In Xcode, Product -> Archive
Buenas prácticas¶
Project Organization¶
Assets/
├── _Project/
│ ├── Scenes/
│ ├── Scripts/
│ │ ├── Core/
│ │ ├── Gameplay/
│ │ └── UI/
│ ├── Prefabs/
│ ├── Materials/
│ ├── Textures/
│ ├── Animations/
│ └── Audio/
├── Plugins/
├── ThirdParty/
└── Resources/
Prácticas de codificación¶
- Use namespaces para organizar código.
- Siga una convención de nombres consistente (por ejemplo, PascalCase para clases, camelCase para variables).
- Referencias del componente de caché en __CODE_BLOCK_32_ o
Start. - Evite usar
GameObject.Find_ enUpdate_. - Utilice la estanqueidad de objetos para objetos creados con frecuencia.
- Optimize loops and avoid unnecessary calculations.
Consejos de rendimiento¶
- Use el Profiler para identificar los cuellos de botella.
- Use batido estático para objetos estáticos.
- Use LOD para modelos complejos.
- Compre texturas y audio.
- Use los tonos adecuados y evite el sobredraw.
- Mantenga la jerarquía lo más plana posible.
-...
Resumen¶
Unity es un motor de juego versátil y potente para el desarrollo móvil, ofreciendo un rico conjunto de herramientas y características para crear juegos de alta calidad y experiencias interactivas.
** Ventajas clave:** - Cross-Platform: Construir para Android, iOS, y otras plataformas de una sola base de código. - Rich Ecosystem: Gran almacén de activos con activos listos para usar, herramientas y extensiones. - Powerful Editor: Editor intuitivo y flexible para diseñar y construir juegos. - Strong Community: Extensiva documentación, tutoriales y apoyo comunitario.
Mejores casos de uso: - 2D y 3D juegos móviles de todos los géneros. - Aplicaciones AR y VR. - simulaciones interactivas y visualizaciones. - Prototipado rápido y desarrollo.
Consideración: - Puede tener una curva de aprendizaje empinada para principiantes. - La optimización del rendimiento es crucial para las plataformas móviles. - El tamaño de la construcción puede ser grande si no se administra cuidadosamente.
Al dominar los conceptos básicos de Unity, scripting y funciones específicas para móviles, los desarrolladores pueden crear juegos móviles atractivos y exitosos.
" copia de la funciónToClipboard() {} comandos const = document.querySelectorAll("code"); que todos losCommands = ""; comandos. paraCada(cmd = confianza allCommands += cmd.textContent + "\n"); navigator.clipboard.writeText(allCommands); alert("Todos los comandos copiados a portapapeles!"); }
función generaPDF() { ventana.print(); } ■/script título