Unity【入门】重要组件和API
Unity重要组件和API
文章目录
- 1、最小单位GameObject
- 1、成员变量
- 2、静态方法
- 1、代码创建Unity自带几何体 CreatePrimitive
- 2、查找对象
- 3、实例化对象(克隆对象)的方法
- 4、删除对象的方法
- 5、切换场景不移除
- 3、成员方法
- 1、创建空物体
- 2、为对象动态添加脚本(不能new)
- 3、得到脚本
- 4、标签比较
- 5、设置激活失活(false失活,true激活)
- 2、时间相关Time
- 1、时间缩放比例
- 2、帧间隔时间
- 3、游戏开始到现在的时间
- 4、物理帧间隔时间 在FixedUpdate
- 5、帧数
- 3、必不可少Transform
- 1、位置和位移
- 1、必备知识点Vector3基础
- 2、位置
- 3、位移
- 4、思考
- 2、角度和旋转
- 1、角度相关
- 2、旋转相关
- 3、缩放和看向
- 1、缩放
- 2、看向
- 4、父子关系
- 1、获取和设置父对象
- 2、和所有子对象脱离关系
- 3、获取子对象
- 4、子类的操作
- 5、思考 查找子对象的子对象
- 5、坐标转换
- 1、世界坐标转本地坐标
- 2、本地坐标转世界坐标
- 3、思考 坐标转换 TransformPoint
- 4、Input和Screen
- 1、输入相关Input
- 2、屏幕相关Screen
- 5、必不可少Camera
1、最小单位GameObject
1、成员变量
1、名字获取和修改
//print(gameObject.name);
//gameObject.name = "Test4_mod";
print(gameObject.name);
2、查看是否激活
print(gameObject.activeSelf);
3、查看是否为静态
print(gameObject.isStatic);
4、层级
print(gameObject.layer);
5、标签
print(gameObject.tag);
6、位置信息transform
print(transform.position);
2、静态方法
1、代码创建Unity自带几何体 CreatePrimitive
GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
obj.name = "TestCube";
2、查找对象
1、单个查找//通过对象名查找GameObject obj2 = GameObject.Find("TestCube");if (obj2 != null){print(obj2);}else{print("查无此项");}//通过tag来查找GameObject obj3 = GameObject.FindWithTag("Player");if (obj3 != null){print(obj3);}else{print("查无此项");}1、单个查找无法找到失活的对象2、存在多个满足条件时,无法精准找到
2、查找多个对象//通过tag找到多个对象(无法找到失活的对象)GameObject[] objs = GameObject.FindGameObjectsWithTag("Player");print(objs);//找到场景中挂载的某个脚本对象Test4 t = GameObject.FindObjectOfType<Test4>();print(t.gameObject.name);Unity中的Object:命名空间在UnityEngine中,是集成万物之父的一个自定义类
C#中的object:命名空间在System中,两者不同
3、实例化对象(克隆对象)的方法
准备用来克隆的对象1、直接是场景上的某个对象2、可以是一个预设体对象public GameObject myObj;克隆动态创建,包含脚本等GameObject.Instantiate(myObj);//若继承了MonoBehavior,则Instantiate(myObj);
4、删除对象的方法
GameObject.Destroy(obj5);
延时删除
GameObject.Destroy(obj5,5);
删除指定脚本
Destroy(this.gameObject);
//Destroy会在下一帧移除
5、切换场景不移除
DontDestroyOnLoad(this.gameObject);
3、成员方法
1、创建空物体
GameObject obj = new GameObject();
GameObject obj1 = new GameObject("byCodeCreate"); //命名
GameObject obj2 = new GameObject("加脚本的物体",typeof(Test4)); //加脚本
2、为对象动态添加脚本(不能new)
Test4 ts3 = obj1.AddComponent(typeof(Test4)) as Test4;
Test4 ts4 = obj1.AddComponent<Test4>();
3、得到脚本
得到脚本的成员方法和继承Mono的类得到脚本的方法一样
4、标签比较
if (this.gameObject.CompareTag("Player"))
{print("对象的标签是Player");
}if (this.gameObject.tag == "Player")
{print("对象的标签是Player");
}
5、设置激活失活(false失活,true激活)
obj1.SetActive(false);
了解其他的成员方法
//通知自己执行所有TestFun方法
gameObject.SendMessage("TestFun");
//广播自己及子类执行所有TestFun方法
gameObject.BroadcastMessage("TestFun");
//广播自己及父类执行所有TestFun方法
gameObject.SendMessageUpwards("TestFun");
2、时间相关Time
用于游戏中参与位移、计时、时间暂停等
1、时间缩放比例
//时间停止
Time.timeScale = 0;
//回复正常
Time.timeScale = 1;
//2倍速
Time.timeScale = 2;
2、帧间隔时间
概念:最近的一帧,用了多长时间(秒)
帧间隔时间,主要用来计算位移
//受timeScale影响
print(Time.deltaTime);
//不受timeScale影响
print(Time.unscaledDeltaTime);
3、游戏开始到现在的时间
print(Time.time);
print(Time.unscaledTime);
4、物理帧间隔时间 在FixedUpdate
设置步长:Edit -> Project Settiongs -> Time
void FixedUpdate()
{print(Time.fixedDeltaTime);print(Time.fixedUnscaledDeltaTime);
}
5、帧数
游戏从开始到现在跑了多少帧(循环)
print(Time.frameCount);
3、必不可少Transform
游戏对象(GameObject)位移、旋转、缩放、父子关系、坐标转换等相关操作都由它处理
它是Unity提供的及其重要的类
1、位置和位移
1、必备知识点Vector3基础
Vector3主要是用来表示三维坐标系中的一个点或者一个向量
声明Vector3 v = new Vector3();//只传x,y,默认z是0Vector3 v2 = new Vector3(10,10);Vector3 v3 = new Vector3(10,10,10);Vector3 v4;Vector的基本计算 + - * /Vector3 v4 = new Vector3(20,20,20);print(v3 + v4);print(v3 - v4);print(v3 * 2);print(v3 / 2);常用print(Vector3.zero); //0,0,0print(Vector3.right); //1,0,0print(Vector3.left); //-1,0,0print(Vector3.forward); //0,0,1print(Vector3.back); //0,0,-1print(Vector3.up); //0,1,0print(Vector3.down); //0,-1,0计算两个点之间的距离Vector3.Distance(v3, v4);
2、位置
相对世界坐标系print(this.transform.position);
相对父对象的坐标(面板值)print(this.transform.localPosition);position和localPosition一样的情况:1、父对象坐标为世界坐标系原点0,0,02、对象没有父对象//注意:位置的赋值不能直接改变x,y,z;只能整体改变transform.position = new Vector3(10, 10, 10);transform.localPosition = Vector3.up * 10;如果只想改一个值x,y和z不变1、直接赋值transform.position = new Vector3(13, transform.position.y, transform.position.z);2、先取出,再赋值Vector3 vPos = transform.localPosition;vPos.x = 13;transform.localPosition = vPos;
对象当前的各朝向print(transform.forward);print(transform.right);
3、位移
//方式一:自己计算
//路程 = 方向 * 速度 * 时间
//相对自己的方向移动
transform.position += transform.forward * Time.deltaTime;
//相对世界坐标方向移动
transform.position += Vector3.forward * Time.deltaTime;//方式二:通过API
//参数一:表示位移多少
//参数二:表示相对坐标系 (默认该参数是相对于自己坐标系)//1、相对于世界坐标系的z轴移动(始终是朝世界坐标系的z轴正方向移动)
transform.Translate(Vector3.forward * Time.deltaTime, Space.World);
//2、相对于世界坐标的 自己的面朝向移动(始终朝自己的面朝向移动)
transform.Translate(transform.forward * Time.deltaTime, Space.World);
//3、相对于自己的坐标系下的 自己的面朝向向量移动(错误移动)
//transform.Translate(transform.forward * Time.deltaTime, Space.Self);
//4、相对于自己的坐标系下的 Z轴正方向移动 (始终朝自己的面朝向移动)
transform.Translate(Vector3.forward * Time.deltaTime, Space.Self);
4、思考
一个空对象上挂一个脚本,在游戏运行时创建一个n层Cube构成的金字塔
//层数
public int n = 1;
// Start is called before the first frame update
void Start()
{//外层循环决定层数for (int i = 0; i < n; i++){//每层开始创建时,得到初始坐标Vector3 pos = new Vector3(-0.5f * i, -1 * i, 0.5f * i);//内层循环决定个数for (int j = 0; j < (i + 1) * (i + 1); j++){//实例化立方体GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);//设置位置obj.transform.position = pos + new Vector3(j % (i + 1) * 1, 0, j / (i + 1) * -1);}}
}
2、角度和旋转
1、角度相关
相对世界坐标角度print(transform.eulerAngles);
相对父对象角度(面板值)print(transform.localEulerAngles);修改相对世界坐标值transform.eulerAngles = new Vector3(10, 45, 60);
修改相对父对象坐标值(面板值)transform.localEulerAngles = new Vector3(10, 45, 60);
//不能单独设置某一个值
2、旋转相关
API
1、自转//第一个参数:每一帧旋转的角度//第二个参数:默认不填,相对于自己坐标系进行旋转transform.Rotate(new Vector3(0,45,0)*Time.deltaTime);transform.Rotate(new Vector3(0,45,0)*Time.deltaTime,Space.World);相对于某个轴旋转//参数一:某个轴旋转//参数二:旋转角度//参数三:默认不填,相对自己坐标系旋转transform.Rotate(Vector3.right,10*Time.deltaTime);transform.Rotate(Vector3.right,10*Time.deltaTime,Space.World);2、相对一个点旋转(公转)transform.RotateAround(Vector3.zero,Vector3.up, 10 * Time.deltaTime);
3、缩放和看向
1、缩放
//相对世界坐标系
print(transform.lossyScale);
//相对本地坐标系(父对象)
print(transform.localScale);//缩放只能一起改(相对世界坐标系的缩放只能得,不能改)
transform.localScale = new Vector3(3, 3,3);
//Unity缩放没有API,需要自己计算
transform.localScale += Vector3.one * Time.deltaTime;
2、看向
让一个对象得面朝向,可以一直看向某一个点或者某一个对象//看向一个点,相对于世界坐标系transform.LookAt(Vector3.zero);//看向一个对象transform.LookAt(lookAtObj);
4、父子关系
1、获取和设置父对象
//获取父对象
print(transform.parent.name);
//脱离父子关系
transform.parent =null;
//设置新的父对象
transform.parent = GameObject.Find("Father2").transform;
通过API设置
//脱离父子关系
transform.SetParent(null);//设置新的父对象
transform.SetParent(GameObject.Find("Father2").transform);
//参数一:父类
//参数二:是否保留世界坐标的位置、角度、缩放信息
//true 会保留世界坐标下的状态和父对象进行计算,得到本地坐标系的信息
//false不会保留,会直接把世界坐标系下的位置角度、缩放直接赋值到本地坐标系下
2、和所有子对象脱离关系
transform.DetachChildren();
3、获取子对象
按名字查找子对象
print(transform.Find("Cube").name);
//失活也能找到,不能找到子类的子类
遍历子对象
子类数量//得到子类数量(失活的也算数量,只会找子类,子类的子类不算数量)print(transform.childCount);//返回值是transform,可以得到对应子类的位置相关信息transform.GetChild(0);遍历子类for (int i = 0; i < transform.childCount; i++){print(transform.GetChild(i).name);
}
4、子类的操作
判断是否为子类if (son.IsChildOf(transform))print("是子类");
得到作为子类的编号print(son.GetSiblingIndex());
把自己设置为第一个子类son.SetAsFirstSibling();
把自己设置为最后一个子类son.SetAsLastSibling();
把自己设置为指定个子类son.SetSiblingIndex(6);
5、思考 查找子对象的子对象
void Start()
{transform.Sort();print(transform.CustomFind("CustomFind").name);
}
public static class Tools
{//按照子对象名字长短排序public static void Sort(this Transform obj){List<Transform> list = new List<Transform>();for (int i = 0; i < obj.childCount; i++){list.Add(obj.GetChild(i));}list.Sort((a, b) =>{if (a.name.Length < b.name.Length){return -1;}else{return 1;}});for (int i = 0;i< list.Count; i++){list[i].SetSiblingIndex(i);}}//查找子对象的子对象public static Transform CustomFind(this Transform father,string childName){Transform target = null;//先从自己的子对象找target = father.Find(childName);if(target != null)return target;//再在子对象的子对象查找for (int i = 0;i<father.childCount;i++){//通过递归查找target = father.GetChild(i).CustomFind(childName);//找到直接返回if (target != null)return target;}return target;}}
5、坐标转换
1、世界坐标转本地坐标
print(Vector3.forward);
1、世界坐标系的点转换为相对本地坐标系的点,受到缩放影响print(transform.InverseTransformPoint(Vector3.forward));2、世界坐标系的点转换为相对本地坐标系的方向//不受到缩放影响print(transform.InverseTransformDirection(Vector3.forward));//受到缩放影响print(transform.InverseTransformVector(Vector3.forward));
2、本地坐标转世界坐标
1、本地坐标系的点转换为相对世界坐标系的点,受缩放影响print(transform.TransformPoint(Vector3.forward));2、本地坐标系的点转换为相对世界坐标系的方向//不受缩放影响print(transform.TransformDirection(Vector3.forward));//受缩放影响print(transform.TransformDirection(Vector3.forward));
3、思考 坐标转换 TransformPoint
[ContextMenu("左前方创建空物体")]
void TestFun()
{GameObject obj = new GameObject("左前方物体");obj.transform.position = transform.TransformPoint(new Vector3(-1, 0, 1));
}[ContextMenu("面前创建3个球体")]
void TestFunc()
{for (int i = 1; i < 4; i++){GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Sphere);obj.transform.position = transform.TransformPoint(Vector3.forward * i);}
}
4、Input和Screen
1、输入相关Input
1、Input鼠标键盘输入
输入相关内容写在Update中
1、鼠标在屏幕位置Input.mousePosition
2、检测鼠标输入1、鼠标按下时(0左键,1右键,2中键)if(Input.GetMouseButton(0))print("鼠标左键按下了");2、鼠标抬起时if (Input.GetMouseButtonUp(0))print("鼠标抬起");3、鼠标长按或抬起时if (Input.GetMouseButton(0))print("长按");4、滚轮(-1下 ,1上)print(Input.mouseScrollDelta);
3、检测键盘输入1、键盘按下if(Input.GetKeyDown(KeyCode.W))print("W键按下");2、传入字符串的重载if (Input.GetKeyDown("a"))print("A键按下");}3、键盘抬起if (Input.GetKeyUp(KeyCode.W))print("W键抬起");}4、键盘长按if (Input.GetKey(KeyCode.W))print("W键长按");
4、检测默认轴输入(控制移动或旋转)1、鼠标横向轴print(Input.GetAxis("Mouse X"));竖向轴print(Input.GetAxis("Mouse Y"));2、键盘水平轴print(Input.GetAxis("Horizontal"));垂直轴print(Input.GetAxis("Vertical"));注意:GetAxis方法在-1~0~1之间,GetAxisRaw方法只返回-1,0,1
2、 其他
anyKey 是否有任意键或鼠标长按
anykeyDown 是否有任意键或鼠标按下
inputString 这一帧的键盘输入得到手柄的所有按钮名string[] strs = Input.GetJoystickNames();某一个手柄键按下 GetButtonDown某一个手柄键抬起 GetButtonUp某一个手柄键按下 GetButton移动设备触摸相关if (Input.touchCount > 0){Touch t1 = Input.touches[0];//点击print(t1.position);//滑动print(t1.deltaPosition);}是否开启多点触控Input.multiTouchEnabled = false;
陀螺仪(重力感应)开启陀螺仪Input.gyro.enabled = true;重力加速度向量print(Input.gyro.gravity);旋转速度print(Input.gyro.rotationRate);陀螺仪当前的旋转四元数print(Input.gyro.attitude);
3、思考 坦克的移动和旋转
public float moveSpeed = 10;
public float rotateSpeed = 50;
public Transform header;
public float headRotate = 50;
void Update()
{transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime * Input.GetAxis("Vertical"));transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime * Input.GetAxis("Horizontal"));header.Rotate(Vector3.up * headRotate * Time.deltaTime * Input.GetAxis("Mouse X"));
}
2、屏幕相关Screen
1、静态属性
1、常用//当前屏幕分辨率Resolution r = Screen.currentResolution;print($"宽{r.width } ,高{r.height}");//屏幕窗口当前宽高(常用)print(Screen.width);print(Screen.height);//屏幕休眠模式Screen.sleepTimeout = SleepTimeout.SystemSetting;
2、不常用//运行时是否全屏模式Screen.fullScreen = true;//窗口模式(发表设置,一般不用代码)独占全屏 FullScreenMode.ExclusiveFullScreen全屏窗口 FullScreenMode.FullScreenWindow最大化窗口 FullScreenMode.MaximizedWindow窗口模式 FullScreenMode.WindowedScreen.fullScreenMode = FullScreenMode.MaximizedWindow;//移动设备屏幕转向相关Home键在左的横屏Screen.autorotateToLandscapeLeft = true;Home键在右的横屏Screen.autorotateToLandscapeRight = true;Home键在下Screen.autorotateToPortrait = true;Home键在上Screen.autorotateToPortraitUpsideDown = true;
2、静态方法
Screen.SetResolution(Screen.width, Screen.height,true); //是否全屏
3.思考
public Transform pkPos;
public float pkRotateSpeed = 50;
//滚轮控制炮管上下
pkPos.Rotate(Vector3.right * pkRotateSpeed * Time.deltaTime * Input.mousePosition.y);
将Main Camera拖到Tank,关联Main Camera的脚本
//摄像机看向的对象
public Transform target;
public float roundSpeed = 50;
//右键移动鼠标,观察坦克视角
transform.LookAt(target);
if (Input.GetMouseButton(1))
{transform.RotateAround(target.position, Vector3.up, roundSpeed * Time.deltaTime * Input.GetAxis("Mouse X"));
}