您的位置:首页 > 移动开发 > Unity3D

unity 3D 学习笔记代码获得组件 物体 和注意事项

2019-01-29 23:36 507 查看

Component
1 获得当前物体的所有组件

if (GUILayout.Button("ALLLLLLCompt"))
{
var allCompt = GetComponents<Component>();
for (int i = 0; i < allCompt.Length; i++)
{
print(allCompt[i].GetType());
}
}

2获取单个组件
var allCompt = GetComponents();

3获得孩子组件

从自身开始查找 如果自己有则 是第一个 和想象的不一样
从自身开始查找 如果自己有则是第一个 和想象的不一样
GetComponentInChildren<>();
(所有后代)
孙子的组件也可以获得
孙子的组件也可以获得
GetComponentsInChildren<>();
4获得父亲物体组件

从自身开始查找 如果自己有则 是第一个 和想象的不一样
从自身开始查找 如果自己有则是第一个 和想象的不一样
(所有后代)
GetComponentsInParent<>
GetComponentInParent<>

5 比较标签 据说比 物体.tag==“ ”好一点
组件.compareTag("");

Transfrom
1 transform.root
目标物体的根

2 transform.parent
获取父物体

3 transform.SetParent(Transform transform)
设置父物体
当然也可以 transform.parent =

这样移动 设置原来物体的位置不会改变


默认true

改为false 位置改成相对父物体的自己原来的坐标的值
位置改变

4 transfrom.Find(“子物体名称”)
这个只能找孩子 不能找孙子
要找孙子要加 路径

不建议 因为路径容易改变
5解除所有子物体(爸爸不要孩子)

7孩子不要爸爸
transfrom.parent==null;
8递归 查询所有的物体

public static GameObject FindChild(Transform parent, string name)
{
if (parent.childCount > 0)
{
for (int i = 0; i < parent.childCount;)
{
if (parent.GetChild(i).name == name)
{
return parent.GetChild(i).gameObject;
}
else
{
if (FindChild(parent.GetChild(i), name) == null)
{
i++;
}
else
{
return FindChild(parent.GetChild(i), name);
};

}

}
}

GameObject
1查找物体的名称(在所有的游戏物体中查找)
GameObject.Find(“xxx”);
太强大 不建议使用
不同于transfrom.Find

2获取所有相同标签的物体

tag必须存在 不然报错(在标签中存在)

3单个 不要s

Obiect

1找场景中所有的相同组件的对象
不管啥父子关系
FindObjectsOfType();

2 克隆方法


创建对于世界坐标

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: