Unity C# 进阶语法
1. 委托与事件
委托 (Delegate)
csharp
public delegate void MyDelegate(string message);
void Start() {
MyDelegate del = PrintMessage;
del("Hello, Delegate!");
}
void PrintMessage(string msg) {
Debug.Log(msg);
}
事件 (Event)
csharp
public class EventPublisher : MonoBehaviour {
public delegate void MyEventHandler(string message);
public event MyEventHandler OnEvent;
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
OnEvent?.Invoke("Space pressed!");
}
}
}
2. LINQ 查询
csharp
using System.Linq;
void Start() {
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var query = from num in numbers
where num % 2 == 0
select num;
foreach (var num in query) {
Debug.Log(num);
}
}
3. 协程 (Coroutine)
csharp
IEnumerator Countdown(int seconds) {
while (seconds > 0) {
Debug.Log(seconds);
yield return new WaitForSeconds(1);
seconds--;
}
Debug.Log("Countdown finished!");
}
void Start() {
StartCoroutine(Countdown(5));
}
4. 属性与索引器
属性 (Property)
csharp
private float speed;
public float Speed {
get { return speed; }
set { speed = Mathf.Clamp(value, 0, 100); }
}
索引器 (Indexer)
csharp
private string[] names = new string[10];
public string this[int index] {
get { return names[index]; }
set { names[index] = value; }
}
5. Unity 特有功能
ScriptableObject
csharp
[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")]
public class Item : ScriptableObject {
public string itemName;
public Sprite icon;
public int value;
}
Editor 扩展
csharp
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(MyComponent))]
public class MyComponentEditor : Editor {
public override void OnInspectorGUI() {
base.OnInspectorGUI();
if (GUILayout.Button("Custom Button")) {
Debug.Log("Button clicked!");
}
}
}
#endif
6. 扩展方法
csharp
public static class ExtensionMethods {
public static void ResetTransform(this Transform t) {
t.position = Vector3.zero;
t.rotation = Quaternion.identity;
t.localScale = Vector3.one;
}
}
// 使用
void Start() {
transform.ResetTransform();
}
7. 异步编程 (async/await)
csharp
using System.Threading.Tasks;
async void Start() {
Debug.Log("Start loading...");
await LoadDataAsync();
Debug.Log("Data loaded!");
}
async Task LoadDataAsync() {
await Task.Delay(2000); // 模拟耗时操作
}
总结
Unity C# 提供了许多强大的高级特性,合理使用这些特性可以:
- 提高代码的可读性和可维护性
- 实现更复杂的功能
- 优化性能
- 扩展Unity编辑器功能