Unity教程:C# 基础

1、Unity脚本基础框架

//脚本中需要使用的Unity库
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//定义脚本类,继承自MonoBehaviour类
public class SimpleControl : MonoBehaviour
{
    public void Start()
    {
		Debug.Log("Start函数,在游戏开始时运行一次");
    }

    void Update()
    {
		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 = new Vector3(1,1,1);

3、C#基础——条件

//(1)if条件语句
if (a==1)
{

}else if (a != 2)
{

}
else
{

}

//(2)switch条件语句
switch (a)
{
    case 1:
    case 2:
        //执行语句
        break;
    case 3:
        //执行语句
        break;
    default:
        //执行语句
        break;
}

4、C#基础——循环

int[] array = { 1, 2, 3, 4, 5 };
int[] temp=new int[5];

//(1)for循环语句
for(int i = 0; i <= 5; i++)
{
    temp[i] = array[i];
}

//(2)while循环语句
int j = 0;
while (j <= 5)
{
	temp[j] = array[j];
    j++;
}

5、C#基础——函数/方法

//方法定义:访问类型;返回类型;函数名;参数
public int MyFunction(int num1,int num2)
{
	return num1 + num2;
}

//方法调用
int a = 1, b = 2;
int c = MyFunction(a, b);

6、C#基础——类

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

//类:一种自己定义的复杂数据类型的模板
//对象:用类创建出来的实例
public class Person
{
	//类的成员变量
	public string name = "Zhao";
	private int age = 18;

	//类的成员函数
	public void setName(string str)
	{
		name = str;
	}

	public int getAge()
	{
		return age;
	}

	//类的构造函数
	public Person()
	{
		name = "";
		age = 10;
	}

	//构造函数重载
	public Person(string str,int num)
	{
		name = str;
		age = num;
	}

}

public class SimpleControl : MonoBehaviour
{
	public Person person1;
	public Person person2;
	
	public void Start()
	{
		//创建对象
		person1 = new Person();
		person2 = new Person("Zhao", 18);

		person1.name = "Sun";
		person1.setName("Sun");

		//Debug.Log(person1.age);
		Debug.Log(person1.getAge());
	}
}
  • 4
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值