C#在Unity中的基础学习笔记

322 阅读1分钟

写在最前面

年轻的时候喜欢打游戏,现在想自己做游戏试试看~~~

学习的是Unity,自然就要学习C#语法了

活到老学到老!

快速访问


基础语法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public Transform target;

    public int health = 99;// 整数类型
    public float speed = 5.5f;// 小数类型
    public bool isJump;// 布尔类型 不写默认 false
    public string color;

    int[] nums = new int[3];// 长度为3个的数组 数据都是整数类型
    string[] names = { "oy", "oldyellow", "老黄" };// 字符串类型的数组
    GameObject[] objects;// 可定义n个 GameObject 引用

    private void Awake()// 无论脚本是否启动都会被运行
    {
        Debug.Log("Awake!");
    }

    // Start is called before the first frame update
    void Start()// 首次运行一次
    {
        Debug.Log("Start!");
        MyInfo("OY", 18, true);

        for (int i = 0; i < 5; i++)
        {
            Debug.Log(i);
        }

        while (transform.position.x < target.position.x)
        {
            Debug.Log("Moving!");
            transform.position = new Vector2(transform.position.x + speed, 0);
        }

        do
        {
            Debug.Log("不管条件是否符合都会实行一次!");
        } while (health > 999);

        switch (color)// 只能判断固定值
        {
            case "Purple":
                Debug.Log("史诗卡牌!");
                break;
            case "Gold":
                Debug.Log("传说卡牌!");
                break;
            default:
                Debug.Log("下次再来!");
                break;
        }
    }

    // Update is called once per frame
    void Update()// 根据你电脑每秒帧率运行 如果60帧电脑 每秒运行60次
    {
        Movement();
    }

    // 物理钢体运动适合使用 每0.02秒执行一次
    private void FixedUpdate()
    {
        // Debug.Log("------");
    }

    private void LateUpdate()
    {
        // Debug.Log("++++++");
    }

    private void OnDestroy()
    {
        Debug.Log("OnDestroy!");
    }

    void Movement()
    {
        if (Input.GetKeyDown(KeyCode.D))
        {
            transform.position = new Vector2(transform.position.x + speed, 0);
        }
    }

    void MyInfo(string fullName, int age, bool isBoy)// 无返回值的函数
    {
        Debug.Log(fullName + age + isBoy);
        Debug.Log(YearOfBorn(age));
    }

    int YearOfBorn(int age)// 有返回值的函数 返回类型写在函数名前
    {
        return 2022 - age;
    }
}


持续更新