Bỏ qua để đến nội dung

Unity C# cơ bản

Unity dùng C# script gắn lên GameObject. Các method như Start, Update, FixedUpdate được Unity gọi theo vòng đời game.

using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float speed = 5f;
void Start()
{
Debug.Log("Ready");
}
void Update()
{
float x = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * x * speed * Time.deltaTime);
}
}
APIGhi nhớ
MonoBehaviourBase class cho Unity script
StartChạy một lần khi object bắt đầu
UpdateChạy mỗi frame
FixedUpdateChạy theo physics tick
[SerializeField]Hiện private field trong Inspector
GameObjectObject trong scene
TransformVị trí, xoay, scale
RigidbodyPhysics body
ColliderVùng va chạm
InstantiateTạo object
DestroyXóa object
CoroutineChạy logic theo thời gian
MethodKhi Unity gọiDùng để
AwakeKhi component được loadCache reference, init sớm
OnEnableKhi component active/enabledSubscribe event
StartTrước frame update đầu tiênInit cần object khác đã Awake
UpdateMỗi frameInput, logic theo frame
FixedUpdateTheo physics tickRigidbody/physics
LateUpdateSau UpdateCamera follow
OnDisableKhi component disabledUnsubscribe event
OnDestroyTrước khi object bị destroyCleanup
private Rigidbody rb = null!;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.MovePosition(rb.position + Vector3.forward * Time.fixedDeltaTime);
}
float horizontal = Input.GetAxisRaw("Horizontal");
Vector3 move = new(horizontal, 0f, 0f);
transform.Translate(move * speed * Time.deltaTime);
Giá trịDùng khi
Time.deltaTimeDi chuyển theo frame trong Update
Time.fixedDeltaTimePhysics trong FixedUpdate
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Coin"))
{
Destroy(other.gameObject);
}
}
void OnCollisionEnter(Collision collision)
{
Debug.Log(collision.gameObject.name);
}
public class PlayerMove2D : MonoBehaviour
{
[SerializeField] private float speed = 5f;
void Update()
{
Vector2 input = new(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
transform.Translate(input.normalized * speed * Time.deltaTime);
}
}
public class PlayerMove3D : MonoBehaviour
{
[SerializeField] private float speed = 5f;
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 move = new(h, 0f, v).normalized;
transform.Translate(move * speed * Time.deltaTime);
}
}
public class Jump : MonoBehaviour
{
[SerializeField] private float force = 6f;
private Rigidbody rb = null!;
void Awake() => rb = GetComponent<Rigidbody>();
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * force, ForceMode.Impulse);
}
}
}
public class Health : MonoBehaviour
{
[SerializeField] private int maxHealth = 100;
private int currentHealth;
void Awake() => currentHealth = maxHealth;
public void TakeDamage(int damage)
{
currentHealth -= damage;
if (currentHealth <= 0) Destroy(gameObject);
}
}
IEnumerator SpawnAfterDelay(GameObject prefab)
{
yield return new WaitForSeconds(2f);
Instantiate(prefab, transform.position, Quaternion.identity);
}
public class Spawner : MonoBehaviour
{
[SerializeField] private GameObject prefab = null!;
public void Spawn()
{
Instantiate(prefab, transform.position, Quaternion.identity);
}
}
public class CameraFollow : MonoBehaviour
{
[SerializeField] private Transform target = null!;
[SerializeField] private Vector3 offset = new(0f, 5f, -8f);
void LateUpdate()
{
transform.position = target.position + offset;
}
}
  • Di chuyển physics trong Update thay vì FixedUpdate.
  • Quên nhân Time.deltaTime khiến tốc độ phụ thuộc FPS.
  • Gọi GetComponent liên tục trong Update.
  • Dùng DestroyImmediate khi đang Play Mode; thường dùng Destroy.
  • So sánh tag bằng other.tag == "Player"; nên dùng CompareTag.
  • Subscribe event trong OnEnable nhưng quên unsubscribe trong OnDisable.
  • Quên kéo prefab/reference vào Inspector cho field [SerializeField].

Unity C#, MonoBehaviour, Awake, Start, Update, FixedUpdate, LateUpdate, OnEnable, OnDisable, SerializeField, GameObject, Transform, Rigidbody, Collider, OnTriggerEnter, OnCollisionEnter, Instantiate, Destroy, Coroutine, Camera follow, unity movement, di chuyển nhân vật