public int hp = 200;
public变量会作为游戏物体的属性显示在属性面板上。之后,在C#代码中初始化变量的值发生改变,属性面板上变量值不会发生变化。变量实际值以属性面板上的值为准
但是,在start()或者update()方法中更新变量的值,变量的值和属性面板上的值都会变化
private int mp = 100;
私有变量的值不会显示在属性面板上
public GameObject cube1;
游戏物体类型的变量可以通过物体拖拽进行赋值。
以这个Cube游戏物体为例,获取它的Transform组件,Collider组件(两个)可以采用如下方法:
void Start()
{
Transform t = GetComponent<Transform>();
Collider[] colliders = GetComponents<Collider>();
print(t);
foreach(Collider temp in colliders)
{
print(temp);
}
}
GetComponent用于获取游戏物体单个组件,GetComponents用于获取一系列的组件
首先,声明一个游戏物体变量,通过拖拽赋值。接着,使用GameObject. GetComponent访问组件
public class Csharp_study : MonoBehaviour
{
public GameObject cube1;
// Start is called before the first frame update
void Start()
{
Transform t1 = cube1.GetComponent<Transform>();
print(t1);
}
}
首先访问组件,接着使用如下命令(Component.enabled=true or false)禁用/启用组件
public class Csharp_study : MonoBehaviour
{
public int hp = 50;
private int mp = 50;
public GameObject cube1;
// Start is called before the first frame update
void Start()
{
BoxCollider collider = cube1.GetComponent<BoxCollider>();
collider.enabled = false;//false 是禁用, true 激活
}
}
void Start()
{
print(transform.Find("Cube1"));//引号下跟路径名
}
public class Csharp_study : MonoBehaviour
{
private GameObject cube1;
// Start is called before the first frame update
void Start()
{
cube1 = GameObject.Find("Cube1");
BoxCollider collider = cube1.GetComponent<BoxCollider>();
print(collider);
}
}
不能有重名物体,且比较耗费性能
public class Csharp_study : MonoBehaviour
{
private GameObject cube1;
// Start is called before the first frame update
void Start()
{
cube1 = GameObject.FindWithTag("Player");
BoxCollider collider = cube1.GetComponent<BoxCollider>();
print(collider);
}
}
绿色框的箭头表示逐语句调试,红色框箭头表示逐过程调试
示例:
using System;
namespace _041_错误处理
{
class Program
{
static void Main(string[] args)
{
int[] myArr = { 1, 2, 3, 4 };
try
{
int num = Convert.ToInt32(Console.ReadLine());
int temp = myArr[num];
}
catch(IndexOutOfRangeException e)
{
Console.WriteLine("出现数组下标越界异常");
}
finally
{
Console.WriteLine("不管是否出现异常,都会执行");
//finally中一般用来写资源关闭的代码
}
}
}
}
如果不需要指定错误类型,catch后面的括号可以省略
Console.WriteLine("请输入两个数字,每行一个");
int num1, num2;
while (true)
{
try
{
num1 = Convert.ToInt32(Console.ReadLine());
num2 = Convert.ToInt32(Console.ReadLine());
break;
}
catch (FormatException e)
{
Console.WriteLine("您输入的数据不符合规则,请重新输入");
}
}
Console.WriteLine(num1 + num2);