Unity C# 入门基础知识点整理与实战技巧

发布于:2025-06-13 ⋅ 阅读:(15) ⋅ 点赞:(0)

在 Unity 开发中,C# 是最常用的编程语言之一。本文将围绕入门阶段的核心知识点展开,结合控制台操作与实用技巧,帮助初学者快速掌握基础编程能力。

一、代码组织与基础语法技巧

1. 代码片段收缩技巧

在编写复杂代码时,合理收缩代码片段能提升可读性:

#region 初始化变量区域
int i = 0;
float score = 0.0f;
string playerName = "Player";
#endregion

作用:通过 #region 和 #endregion 标记的代码块可在编辑器中折叠,方便快速定位关键逻辑。

2. 基础语法要点

  • 变量类型与字符长度
    常见类型:int(32 位整数)、float(32 位浮点数)、double(64 位浮点数)、string(字符串)等。

  • 常量声明与特点
    用 const 关键字声明,值不可修改:

    const int MAX_SCORE = 100;  // 游戏最高分
    const string GAME_NAME = "UnityDemo";
    
  • 转义字符
    以 \ 开头,用于特殊字符表示:

    • \n:换行
    • \t:制表符
    • \":双引号
    • \\:反斜杠

二、程序控制核心基础

1. 类型转换

不同数据类型间的转换分为两种:

  • 隐式转换(自动转换,安全类型提升):
    int a = 10;
    double b = a;  // int 自动转为 double
    
  • 显式转换(强制转换,需注意数据丢失):
    double c = 3.9;
    int d = (int)c;  // 结果为 3,小数部分丢失
    

2. 运算符与流程控制

  • 运算符:涵盖算术运算符(+ - * / %)、比较运算符(== > < >= <= !=)、逻辑运算符(&& || !)等。

  • 条件分支语句

    int score = 85;
    if (score >= 90) {
        Console.WriteLine("优秀");
    } else if (score >= 70) {
        Console.WriteLine("良好");
    } else {
        Console.WriteLine("及格");
    }
    
  • 循环语句

    // for 循环:打印1-10
    for (int i = 1; i <= 10; i++) {
        Console.WriteLine(i);
    }
    
    // while 循环:随机数猜谜游戏
    Random r = new Random();
    int target = r.Next(1, 101);
    int guess;
    while (true) {
        Console.Write("请猜一个1-100的数字:");
        guess = int.Parse(Console.ReadLine());
        if (guess == target) {
            Console.WriteLine("猜对了!");
            break;
        } else if (guess < target) {
            Console.WriteLine("猜小了");
        } else {
            Console.WriteLine("猜大了");
        }
    }
    

三、控制台操作实用技巧

1. 控制台样式与布局控制

// 1. 设置控制台大小(宽,高)
Console.SetWindowSize(120, 30);

// 2. 设置缓冲区大小(需大于窗口大小,避免滚动卡顿)
Console.SetBufferSize(120, 100);

// 3. 设置光标位置(x, y),左上角为(0,0)
Console.SetCursorPosition(10, 5);
Console.WriteLine("此处开始输出");

// 4. 设置文字与背景颜色
Console.ForegroundColor = ConsoleColor.Red;     // 红色文字
Console.BackgroundColor = ConsoleColor.Magenta; // 紫色背景
Console.WriteLine("醒目提示!");

// 5. 隐藏光标(适合进度条等场景)
Console.CursorVisible = false;

// 6. 关闭控制台程序
Environment.Exit(0); // 0表示正常退出,非0为错误退出

2. 随机数生成实战

// 1. 初始化随机数生成器
Random r = new Random();

// 2. 生成指定范围的随机数(左闭右开区间)
int random1 = r.Next(10);         // 0-9
int random2 = r.Next(5, 15);      // 5-14

// 3. 应用示例:生成随机颜色
ConsoleColor[] colors = {
    ConsoleColor.Red, ConsoleColor.Green, 
    ConsoleColor.Blue, ConsoleColor.Yellow
};
Console.ForegroundColor = colors[r.Next(0, colors.Length)];
Console.WriteLine("随机颜色文本");

四、异常捕获与程序健壮性

在代码执行中,异常处理能防止程序崩溃:

try {
    Console.Write("请输入数字:");
    int num = int.Parse(Console.ReadLine());
    int result = 100 / num;
    Console.WriteLine("100 / " + num + " = " + result);
} catch (FormatException) {
    Console.WriteLine("输入格式错误,请输入数字!");
} catch (DivideByZeroException) {
    Console.WriteLine("不能除以0!");
} catch (Exception e) {
    Console.WriteLine("发生错误:" + e.Message);
} finally {
    Console.WriteLine("无论是否出错,都会执行这里");
}

总结

本文梳理了 Unity C# 入门阶段的核心知识点,包括代码组织、基础语法、流程控制、控制台操作与异常处理。这些内容是后续 Unity 游戏开发的基石,建议通过实战练习加深理解(例如结合控制台实现简单的猜谜游戏、计算器程序等)。

在实际开发中,可进一步结合 Unity 引擎特性,将控制台逻辑迁移到游戏场景中,例如用随机数生成敌人位置、用条件判断实现交互逻辑等。持续积累基础,才能更顺畅地进阶到高级开发技巧。

最后附上一个简单的通过循环与随机数写的文字回合制小实列给大家 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lesson_循环与随机数的使用
{
    class Program
    {
        

        static void Main(string[] args)
        {
            string guaiShou = "敌人";
            int HP = 20;
            int DP = 10;

            string player = "主角";
            Random r = new Random();

            int j = 1;

            for (int i = HP; i >0;)
            {
                    int AP = r.Next(1, 13);

                    Console.WriteLine("第" + j + "回合");
                    j++;
                    Console.WriteLine(player + " 对 " + guaiShou + " 发起了攻击。");
                    Console.WriteLine(player + " 的攻击力为" + AP + "," + guaiShou + "的防御力为" + DP + "。");
                    if (AP - DP > 0)
                    {
                        int c = AP - DP;
                        Console.WriteLine("本次成功造成伤害为" + c);
                        i -= c;
                        Console.WriteLine(guaiShou + "剩余血量" + i);
                        Console.WriteLine("\n");

                    }
                    else
                    {

                        Console.WriteLine("本次成功造成伤害为" + 0);
                        Console.WriteLine(guaiShou + "剩余血量" + i);
                        Console.WriteLine("\n");

                    }
                


            }
            Console.WriteLine("恭喜" + player + "成功击杀了" + guaiShou);



        }




    }
}

 我后续也将继续发布更深入的C#学习知识