Skip to content
On this page

Unity中的C#类(Class) ​

基本概念 ​

类定义 ​

csharp
public class Player 
{
    // 成员变量
    public string name;
    private int health;
    
    // 构造函数
    public Player(string playerName, int initialHealth)
    {
        name = playerName;
        health = initialHealth;
    }
    
    // 方法
    public void TakeDamage(int damage)
    {
        health -= damage;
    }
}

MonoBehaviour类 ​

Unity中所有脚本都继承自MonoBehaviour类:

csharp
using UnityEngine;

public class PlayerController : MonoBehaviour 
{
    // Unity生命周期方法
    void Start() {}
    void Update() {}
}

面向对象特性 ​

继承 ​

csharp
public class Enemy : MonoBehaviour 
{
    public int damage;
    
    public virtual void Attack() 
    {
        Debug.Log("Enemy attacks!");
    }
}

public class Boss : Enemy 
{
    public override void Attack() 
    {
        base.Attack();
        Debug.Log("Boss special attack!");
    }
}

抽象类与接口 ​

csharp
public abstract class Weapon 
{
    public abstract void Fire();
}

public interface IDamageable 
{
    void TakeDamage(int damage);
}

实用技巧 ​

  1. 使用[Serializable]标记可序列化的类
  2. 使用[System.Serializable]创建自定义数据结构
  3. 静态类用于工具方法
  4. 单例模式在Unity中的实现

总结 ​

C#类是Unity开发的核心,掌握面向对象编程和MonoBehaviour特性是成为优秀Unity开发者的基础。

Released under the MIT License.