image1 image2 image3

HELLO I'M VIET|WELCOME TO MY PERSONAL BLOG|I LOVE TO DO CREATIVE THINGS

Unity bài 5: Classes và Objects


Nội dung bài viết
  1. Tạo đối tượng trong Class
  2. Constructor và Function


I. Tạo đối tượng trong Class

  • Trong class Introduce, tạo các thuộc tính name, health, speed.

public class Introduce : MonoBehaviour
{
    string name = "Tran Viet";
    int health = 100;
    int speed = 10;
    void Start()
    {
        Introduce intro = new Introduce();
        intro.Move();
        intro.Attack();
    }
    void Update()
    {
    }
    void Move()
    {
        Debug.Log("Thay player is moving");
    }
    void Attack()
    {
        Debug.Log("The player is attacking");
    }
}

II. Constructor trong Class

  • Bạn có thể custom Constructor cho mình như sau:
    public Introduce(string nameint healthint speed){
        this.name = name;
        this.health = health;
        this.speed = speed;
    }
  • Function
    int myInt = 5;
    void Start ()
    {
        myInt = MultiplyByTwo(myInt);
        Debug.Log (myInt);
    }
    int MultiplyByTwo (int number)
    {
        int ret;
        ret = number * 2;
        return ret;
    }

Kết quả của Function là 10


Các bài đã học là những thuật toán cơ bản để trong lập trình, ở bài tiếp theo ta sẽ đến với việc lập trình Game cụ thể.

Share this:

CONVERSATION

0 nhận xét:

Đăng nhận xét

Thank you!