Mecanim 发表于 2022-3-25 18:47

Unity教程:C# 基础

1、Unity脚本基础框架
//脚本中需要使用的Unity库usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;//定义脚本类,继承自MonoBehaviour类publicclassSimpleControl:MonoBehaviour{publicvoidStart(){
                Debug.Log("Start函数,在游戏开始时运行一次");}voidUpdate(){
                Debug.Log("Update函数,游戏运行时每一帧运行一次");}}2、C#基础——数据类型
int num1 =1;int[] array ={0,1,2,3,4};float num2 =1.0f;bool isOpen =true;string str ="This is a String!"Vector3 direction =newVector3(1,1,1);3、C#基础——条件
//(1)if条件语句if(a==1){}elseif(a !=2){}else{}//(2)switch条件语句switch(a){case1:case2://执行语句break;case3://执行语句break;default://执行语句break;}4、C#基础——循环
int[] array ={1,2,3,4,5};int[] temp=newint;//(1)for循环语句for(int i =0; i <=5; i++){
    temp= array;}//(2)while循环语句int j =0;while(j <=5){
        temp= array;
    j++;}5、C#基础——函数/方法
//方法定义:访问类型;返回类型;函数名;参数publicintMyFunction(int num1,int num2){return num1 + num2;}//方法调用int a =1, b =2;int c =MyFunction(a, b);6、C#基础——类
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;//类:一种自己定义的复杂数据类型的模板//对象:用类创建出来的实例publicclassPerson{//类的成员变量publicstring name ="Zhao";privateint age =18;//类的成员函数publicvoidsetName(string str){
                name = str;}publicintgetAge(){return age;}//类的构造函数publicPerson(){
                name ="";
                age =10;}//构造函数重载publicPerson(string str,int num){
                name = str;
                age = num;}}publicclassSimpleControl:MonoBehaviour{publicPerson person1;publicPerson person2;publicvoidStart(){//创建对象
                person1 =newPerson();
                person2 =newPerson("Zhao",18);

                person1.name ="Sun";
                person1.setName("Sun");//Debug.Log(person1.age);
                Debug.Log(person1.getAge());}}
页: [1]
查看完整版本: Unity教程:C# 基础