美文网首页
一、Unity基础—脚本对“游戏对象”的基本操作

一、Unity基础—脚本对“游戏对象”的基本操作

作者: 万恶的意外er | 来源:发表于2018-07-04 20:40 被阅读0次

    游戏对象与脚本联系常紧密,因为游戏对象之间的一切交互都需要使用脚本来完成。

    1. 使用脚本来调用游戏对象的方式有两种:

    1. 将脚本绑定在一个游戏对象上;
    2. 在代码中动态绑定脚本和删除脚本。

    任何一个游戏对象都可以同时绑定多条游戏脚本,并且这些脚本互不干涉,各自完成各自的生命周期。

    2. Unity脚本 和 C#脚本区别?

    • unity脚本继承自MonoBehavior。
    • unity脚本不能new。
    • unity脚本有自己的声明周期。
    • unity脚本作为组件附加在GameObject上面,是GameObject的附加功能(unity的使用是组件模式)

    3.GameObject 和 Transform区别

    • GameObject是游戏对象本身。
    • Transform是一个特殊组件(1.必有组件,2.二者互相可获取,3.方法较多)。

    • GameObject:游戏对象的基本操作
    gameObject.activeSelf 是否活动
    gameObject.tag        标签
    gameObject.layer      层
    gameObject.name       名字
    ...
    
    • Transform:位置,旋转,缩放变换操作
    transform.Position:(位置)
    transform.Rotation:(旋转)
    transform.Scale:(缩放)
    ...
    

    4.脚本操作‘游戏对象’

    • 创建游戏对象
    //创建基本几何体
    GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
    
    • 克隆游戏对象
    //克隆预制体
    GameObject.Instantiate(prefab);
    
    • 查找游戏对象
    1.以名字查找
    GameObject.Find(string);
    2.以标签查找
    GameObject.FindGameObjectWithTag(tag);
    3.以组件查找
    T GameObject.FindObjectOfType<T>() ;
    
    • 销毁游戏对象
    销毁游戏对象,是一个静态方法 
    GameObject.Destroy(gameObject)
    
    • 对象添加组件
    public Component AddComponent <XXX>()
    
    • 获取对象组件
    1.获取自身的组件
    public Component GetComponent<XXX>(bool includeInactive)
    public Component[] GetComponents<XXX>(bool includeInactive)
    2.获取子节点组件
    public Component GetComponentInChildren<XXX>(bool includeInactive)
    public Component[] GetComponenstInChildren<XXX>(bool includeInactive)
    3.获取父节点组件
    public Component GetComponentInParent<XXX>(bool includeInactive)
    public Component[] GetComponentsInParent<XXX>(bool includeInactive)
    
    • 删除对象组件
    //切记没有 RemoveComponent() 方法;
    1.删除游戏组件
    component=go.GetComponnent<XXX>();
    GameObject.Destroy(component);
    

    5.脚本操作Transform

    • 查找子节点
    //获取子节点数量
    transform.childCount
    //按名字(路径)查找
    transform.Find(string);
    transform.FindChild(string);
    //按索引查找
    transform.GetChild(int);
    //分离子节点
    transform.DetachChildren();
    
    • 设置父节点
    //获取根节点
    transform.root
    //获取父节点
    transform.parent
    //设置父节点
    transform.SetParent(transform);
    
    • 物体位移
    transform.Translate(vector3);
    
    • 物体旋转
    //自转
    transform.Rotate(axis,angle);
    //公转
    transform.RotateAround(point,axis,angle);
    
    • 看向目标
    transform.LookAt(transform);
    
    • 转换坐标系
    //变换位置从物体坐标到世界坐标
    transform.TransformPoint(vector3);
    //变换位置从世界坐标到自身坐标
    transform.InverseTransformPoint(vector3);
    //将一个方向从局部坐标变换到世界坐标方向
    transform.TransformDirection(vector3);
    //将一个方向从世界坐标变换到局部坐标方向
    transform.InverseTransformDirection(vector3);
    

    相关文章

      网友评论

          本文标题:一、Unity基础—脚本对“游戏对象”的基本操作

          本文链接:https://www.haomeiwen.com/subject/vwyyuftx.html