(1)Gameobject类
GameObject是Unity场景里面所有实体的基类.
一、查找游戏对象
1. 通过名字查找
GameObject.Find(string name);
此方法每次都会遍历整个场景,来寻找匹配的游戏物体,比较消耗资源
2. 通过Tag(标签)查找对象
Gameobject.FindGameObjectWithTag(string tag);
通过tag标签进行查找
GameObject.FindGameObjectsWithTag(string tag)
查找到所有挂载此标签的对象,并返回一个GameObject数组


二、动态创建删除游戏物体
创建系统内置的游戏对象并且给名字,位置和标签


Capsule 胶囊
Cube 立方体
Cylinder 圆柱体
Plane 平面
Quad 正方形面片
Sphere 球形
*** 实例化游戏对象,通过预制物加载***
GameObject.Instantiate(obj original,Vector3 Position, Quaternion rotation)可以设置位置与旋转
简单版
GameObject.Instantiate(obj original);
简单版则不可以设置位置与旋转,都为默认值(0,0,0)


GameObject.Destroy(Object obj);
其参数或者是(Object obj, float 1f);
此方法可以有一个重载,后面还可以加一个时间参数,就是延时删除
删除完物体,物体还会存在于内存中,调用此方法时,只是给一个标记,内存中依然存在,只有内存不够,或一段时间内没有再次被引用时(或者更多的条件满足),机制才会对他进行销毁并释放内存


三、动态添加组件
1.非泛型
obj.AddComponent(typeof(Animation)); 使用反射添加
2.泛型
obj.AddComponent<T>();
最常用的还是泛型的

运行后球体拥有刚体组件

四、动态获取组件
获取到自己身上的组件
this.getComponent<XXX>();
获取其他物体身上的组件
GameObject.Find(“url”).getComponent<XXX>();

打印输出

五、SendMessage-发送消息:
GameObject.SendMessageUpwards 向上发送消息 ,向物体和父物体发送消息,如果消息没有被任何一个组件处理,则会打印一个错误。
***GameObject.BroadcastMessage ***广播消息,对物体和所有子物体发送消息。如果消息没有被任何一个组件处理,则会打印一个错误。
***GameObject.SendMessage ***发送消息向同级发送消息。果消息没有被任何一个组件处理,则会打印一个错误。

(2)Transform组件


查找根(返回层次最高的transform)
obj.transform.root;
查找到父级
obj.transform.parent;
获得子游戏物体的数量
obj.transform.childCount;
移除所有的子游戏对象(通过这种方式可以摆脱父子级关系)
obj.transform.DetachChildren();
获取某个索引位置的游戏对象
obj.transform.GetChild(index );
Debug.Log("position " + transform.position); //世界坐标的位置
Debug.Log("localPosition " + transform.localPosition); //相对于父位置的坐标 即把父物体当作自己的中心
Debug.Log("eulerAngles " + transform.eulerAngles);//世界坐标欧拉角度
Debug.Log("localEulerAngles " + transform.localEulerAngles);//相对于父级的变换的旋转欧拉角度
Debug.Log("localScale " + transform.localScale);//相对于父位置的缩放
Debug.Log("localRotation " + transform.localRotation);//相对于父位置的旋转
Debug.Log("rotation " + transform.rotation);//世界坐标的旋转
Rotate自转

RotateAround公转

四元数(Quaternion)和旋转
Quaternion又称四元数,由x,y,z和w这四个分量组成,是由爱尔兰数学家威廉·卢云·哈密顿在1843年发现的数学概念。
四元数用于表示旋转,有一种旋转的表示方法叫四元数。
Quaternion rotations = Quaternion.identity;
//第一种方式:将Quaternion实例对象赋值给transform的rotation
rotations.eulerAngles = new Vector3(0.0f, tSpeed, 0.0f);
Quaternion.identity就是指Quaternion(0,0,0,0),就是每旋转前的初始角度,是一个确切的值,而transform.rotation是指本物体的角度,值是不确定的
四元数*vector3(原始位置)=旋转后最新的位置




网友评论