unity常用小知识点

感觉自己抑郁变得更严重了,超级敏感,经常想崩溃大哭,睡眠超差,实在不想药物治疗,多看看书,多约约朋友,多出去走走。

来几句鸡汤吧,人一定要活得明白一点,任何关系都不要不清不楚,说不定最后受伤的就是自个。另外,内心尽量变得强大一点,这样世界便会美好很多。

ok,吐槽到此,开始正题吧,今天说几个unity的常用知识点,最近博客更得比较少,好像更习惯用有道笔记。

1.GetComponentInChildren()、GetComponentsInChildren() 包含自己和所有子对象
 
2.Instantiate
GameObject newGo = Instantiate (GameObject.Find("Cube"),Vector3.zero,Quaternion.identity,GameObject.Find("Father").transform);
newGo 的世界坐标Vector3.zero,世界旋转Quaternion.identity,父对象GameObject.Find("Father").transform
 
3.计算物体大小
总的来说三种方式:分别可通过 MeshRenderer,MeshFilter,collider这3个组件来获取。
 
(1)根据 MeshRenderer这个值的结果 真实反应出有MeshRenderer这个组件的模型的尺寸。不需要再乘以localScale.x。
 
(2)通过MeshFilter获得原始模型的mesh,该值返回的结果是原始mesh的尺寸。
若要获得模型的尺寸大小还需要乘以模型的localScale.x。
即:gameObject.GetComponent<MeshFilter>().mesh.bounds.size.x*gameObject.transform.localScale.x;
 
(3)为物体添加Collider,然后使用XXX.collider.bounds.size;
这个不一定能很好的反应物体的大小,bounds获得的是物体的外包矩形。而且这个外包矩形的X,Y,Z和世界坐标一致。因此,若物体有旋转,获得的尺寸就不能反应出物体的真实大小,只是其外包矩形的大小。。。
如:获得terrain的尺寸
       
 terrainWidth = terrain.collider.bounds.size.x;
 terrainLength = terrain.collider.bounds.size.z;
 terrainHeight = terrain.collider.bounds.size.y; 
个人偏爱 (2)
获取复杂物体的真实尺寸
//计算物体真实尺寸
        public static Vector3 getTargetSizeByRender(GameObject target){
            Vector3 vec = Vector3.one;
            Quaternion localQuaternion = target.transform.rotation;
            target.transform.rotation = Quaternion.identity;
            var renders = target.transform.GetComponentsInChildren<Renderer> ();
            if (renders.Length > 0) {
                Bounds bounds = renders [0].bounds;
                for (int i = 1; i < renders.Length; i++) {
                    bounds.Encapsulate (renders [i].bounds);
                }
                vec = bounds.size;
            }
            target.transform.rotation = localQuaternion;
            return vec;
        }

  当物体中有粒子特效,会影响计算结果,这时判断renders [i]的gameObject是否有粒子系统组件,如果有,将循环continue调就行了。总之,根据自己的项目需求在这个基础上做一些计算优化就行了,多动动脑筋。

 
4.Invoke()
Invoke是一种委托方法。
void Invoke(string methodName, float time) ,第一个参数是要调用的函数名,后一个参数是延迟的时间。
意思为:在time时间后调用函数名为methodName方法。设置完methodName函数的执行时间后,程序会接着往下执行,并不会等methodName函数执行。而协程可以等某个操作完成之后再执行后面的代码。
使用 Invoke() 方法需要注意 3点:
(1)它应该在 脚本的生命周期里的(Start、Update、OnGUI、FixedUpdate、LateUpdate)中被调用;
这个不是很明白,例如下面代码
void Start () {
        Test ();
        Debug.Log ("start");
    }
    void TestInvoke(){
        Debug.Log ("TestInvoke");
    }
    void Test(){
        Debug.Log ("Test");
        Invoke ("TestInvoke",5f);
}
 
中 TestInvoke 可以被调用。
(2)Invoke(); 不能接受含有 参数的方法;
(3)在 Time.ScaleTime = 0; 时, Invoke() 无效,因为它不会被调用到
Invoke() 也支持重复调用:void InvokeRepeating(string methodName, float time, float repeatRate);
意思是指:time秒后调用 调用函数名为methodName方法,并且之后每隔 repeatRate秒调用一次调用函数名为methodName方法。

原文地址:https://www.cnblogs.com/leeplogs/p/8540494.html