C# 

楓資 鄭云晶

-unity-

  • 微軟推出
  • 衍生自C和C++
  • .NET框架
  • 物件導向的進階程式語言

C# (C sharp)

  • 角色控制
  • 血量、分數系統
  • 攻擊、子彈
  • 碰撞判斷

 

  • 桌面程式(計算機、工具)
  • 網站後端(登入、資料庫)
  • 手機 / 跨平台 App
  • 自動化小工具

應用程式開發(.NET

 

遊戲開發(Unity

 

應用

輸入&輸出

using System;

class Program{

    static void Main(){
    	string x=Console.ReadLine();
        Console.WriteLine(x);
    }
}

        印出並換行:Console.WriteLine

        印出:Console.Write

非文字輸入:Console.Read()

字串輸入:Console.ReadLine()

資料型別

int hp = 100;
float speed = 5.5f;
string playerName = "Hi";
bool isAlive = true;
int整數
float浮點數
string字串(參考型別)
char字元
bool布林值

實值型別 (Value Types)

陳述式

static void transnumber(string[] args){
    int a;
    int b = 2, c = 3;
    a = 1;
    Console.WriteLine(a + b + c);
}
static void normalnumber(string[] args){
    const float pi = 3.1415927f;
    const int r = 25;
    Console.WriteLine(pi * r * r);
}
static void math(string[] args){
    int i;
    i = 123;               
    Console.WriteLine(i);   
    i++;                    
    Console.WriteLine(i);  
}

變數宣告

常數宣告
運算式​
static void IfStatement(string[] a){
    if (a.Length == 0){
        Console.WriteLine("No");
    }
    else{
        Console.WriteLine("One or more");
    }
}

條件判斷陳述式

判斷是否為空字串

static void ForStatement(string[] a){
    for (int i = 0; i < a.Length; i++){
        Console.WriteLine(a[i]);
    }
}
static void WhileStatement(string[] a){
    int i = 0;
    while (i < a.Length){
        Console.WriteLine(a[i]);
        i++;
    }
}

While陳述式

For陳述式

把陣列裡的每個元素逐行印出

類別

class

class Player{
    int hp;
    float speed;
    string name;
}

把角色血量變為50

Player p = new Player();
p.hp = 50;

類別

欄位(Fields)

  • 參考型別(Reference Type)
  • 一個封裝數據與功能的容器

類別(class)

屬性

控制欄位怎麼被使用

p.hp = -999;

在讀或改資料時,加一層檢查或規則

class Player{

    private int hp;

    public int Hp{
        get { return hp; }
        set{
            if (value >= 0)
                hp = value;
        }
    }
}

讀取資料

修改資料

public:公開欄位(可以在 Inspector 直接改

private:真正存資料(不能直接改)

屬性

class Player{
    public string name = "哈哈";
    public int hp = 100;

    public void SayHi(){
        Console.WriteLine("你好,我是 " + name);
    }


    public void TakeDamage(int damage){
        hp -= damage;
        Console.WriteLine(name + " 剩餘血量: " + hp);
    }
}

定義一個方法:受傷 (需要傳入傷害值)

    定義一個方法:自我介紹

 

方法(Method)

[存取修飾詞] [回傳類型] [方法名稱] (參數)

呼叫

Player p = new Player();
p.SayHi();             
p.TakeDamage(20);     

你好,我是 哈哈

哈哈 剩餘血量:80

Made with Slides.com