Unity study notes (1) - various operations of objects

  1. Get the object object mounted on the script component

gameObject
  1. Set the visibility of object objects

gameObject.SetActive(true);
gameObject.SetActive(false);
  1. Get object

  1. Get script by name

GameObject.Find("Object");
//1.GameObject.Find(),无法找到未激活的物体
//2.GameObject.Find()需要遍历场景的所有物体,从性能上看是十分低效的。
//注:它是全局查找,所以如果要查找子对象的话,用 transform.Find 更方便。

transform.Find("object name");
//查找下一层次的子物体
//它只会查询Hierarchy中下一层次的物体,不会递归地向下查找
//如果需要获取物体根节点下指定路径的子物体,可以用以下方式:

gameObject.transform.Find("SelectedEffect/遮罩/渐变")
//获取子物体中的组件
  1. Find objects by tag

//以通过物体的标签直接获得物体,使用GameObject.FindGameObjectWithTag()方法即可,可高效地查找物体
//获取第一个标签为Object的物体
GameObject ob = GameObject.FindGameObjectWithTag("Object");
//获取所有标签为Object的物体,返回值是一个数组
GameObject[] obs = GameObject.FindGameObjectsWithTag("Object");
  1. Get components using scripts

//获得其他物体object的刚体
GameObject ob = GameObject.Find("object");
Rigidbody obrb = ob.GetComponent<Rigidbody>();
  1. Move, scale, and rotate objects

//1、移动
//物体向x方向移动1.5个单位
transform.Translate(1.5f,0,0);
//或
transform.position += new Vector3(1.5f,0,0);

//稳定帧率
transform.Translate(1.5f*Time.deltaTime,0,0);
//或
transform.position += new Vector3(1.5f*Time.deltaTime,0,0);

//2、缩放
//cube.transform.localScale *= 1.2f;

//3、旋转
//cube.transform.Rotate (new Vector3(0, 10, 0));
//围绕球体旋转物体
//cube.transform.RotateAround (cylinder.transform.position, Vector3.up, 10);
  1. Move objects via keyboard

float horizontal = Input.GetAxis("Horizontal");
float vetical = Input.GetAxis("Vetical");
 
transform.Translate(horizontal*speed*Time.deltaTime,vetical*speed*Time.deltaTime,0);
//或
transform.position += new Vector3(horizontal*speed*Time.deltaTime,vetical*speed*Time.deltaTime,0);

Guess you like

Origin blog.csdn.net/ximi2231/article/details/129517551