Unity C# 基础语法
1. 变量与数据类型
csharp
// 基本数据类型
int score = 100; // 整数
float speed = 5.5f; // 浮点数
bool isGameOver = false; // 布尔值
string playerName = "Player1"; // 字符串
// Unity特有类型
Vector3 position = new Vector3(1, 2, 3);
GameObject player;
2. 方法与函数
csharp
// 基本方法
void MovePlayer(float speed) {
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
// 带返回值的方法
int CalculateScore(int baseScore, int multiplier) {
return baseScore * multiplier;
}
3. 类与对象
csharp
public class Player {
// 成员变量
public string name;
private int health;
// 构造函数
public Player(string playerName) {
name = playerName;
health = 100;
}
// 成员方法
public void TakeDamage(int damage) {
health -= damage;
}
}
4. 继承与多态
csharp
public class Enemy : MonoBehaviour {
public virtual void Attack() {
Debug.Log("Enemy attacks!");
}
}
public class Boss : Enemy {
public override void Attack() {
base.Attack(); // 调用父类方法
Debug.Log("Boss special attack!");
}
}
5. 接口
csharp
public interface IDamageable {
void TakeDamage(int damage);
}
public class Player : MonoBehaviour, IDamageable {
public void TakeDamage(int damage) {
// 实现接口方法
}
}
6. MonoBehaviour生命周期
csharp
public class Example : MonoBehaviour {
// 初始化
void Awake() { }
void Start() { }
// 每帧更新
void Update() { }
void FixedUpdate() { }
void LateUpdate() { }
// 物理相关
void OnCollisionEnter(Collision collision) { }
// 销毁
void OnDestroy() { }
}
7. 协程
csharp
IEnumerator Countdown() {
for(int i = 3; i > 0; i--) {
Debug.Log(i);
yield return new WaitForSeconds(1);
}
Debug.Log("Start!");
}
void Start() {
StartCoroutine(Countdown());
}
8. 常用Unity API
csharp
// 获取组件
GetComponent<Rigidbody>();
// 实例化对象
Instantiate(prefab, position, rotation);
// 查找对象
GameObject.Find("Player");
// 加载资源
Resources.Load<Sprite>("Sprites/player");