视频笔记-Unity脚本-Component类,Transform类-P120~P124

原视频链接

核心类

核心类图


Component 类

两种制作按钮的方式

    void OnGUI()
    {	// 四个参数分别是按钮左上顶点的向右偏移,向下偏移,按钮宽度,高度
        if (GUI.Button(new Rect(0, 100, 50, 200), "I am a button"))
        {
            print("You clicked the button!");
        }
        if (GUILayout.Button("I am a button"))
        {
            print("You clicked the button!");
        }
    }

两种方式分别对应两种组织 UI 界面的方式:Fixed Layout vs Automatic Layout

点击改变物体颜色

    void OnGUI()
    {
        if (GUILayout.Button("Turn color"))
            GetComponent<Renderer>().material.color = new Color(1, 0, 0, 1);
    }

获取物体的所有组件

    void OnGUI()
    {
        if (GUILayout.Button("Get Components"))
        {
            Component[] components = GetComponents<Component>();
            foreach (var item in components)
                print(item);
        }
    }

获取物体及其所有子物体的组件

获取顺序采用深度优先搜索

    void OnGUI()
    {
        if (GUILayout.Button("Get Components"))
        {
            var components = this.GetComponentsInChildren<MeshRenderer>();
            foreach (var item in components)
            {
                item.material.color = Color.red;
            }
        }
    }

总结:Component 类提供了(在当前物体、后代、先辈中)查找组件的功能。


Transform 类

遍历所有子物体的变换组件:

    void OnGUI()
    {
        if (GUILayout.Button("foreach - transform"))
        {
            foreach (Transform child in transform)
            {   // child 为每个子物体的变换组件
                print(child.name);
            }
        }
    }

常用属性

注意:编辑器中显示的的位置、旋转、缩放都是 Local 的。

  • positionlocalPosition
  • rotationlocalRotation
  • localScalelossyScale
    编辑器中的缩放指的是相比父物体的缩放比例。
    localScale指的是相对父物体缩放比例;
    lossyScale(只读)指的是物体与原模型缩放比例(自身缩放比例 * 父物体缩放比例)。
  • root:获取根物体变换组件;
  • parent:获取父物体变换组件;
  • childCount:子物体数量。

常用方法

  • Translate:移动;
  • Rotate:旋转;
  • RotateAround:选定点和轴旋转;
  • SetParent:设置父物体,设为 null 即可解除关系;
  • Find:根据名称获取子物体(支持用路径查找孙子,但不推荐);

总结:Transform 类提供了查找(父、根、子)变换组件、改变位置、角度、缩放等功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值