Unity3d基础入门之常用API的总结与解析

常用API(重点)

Ø  介绍: 应用程序编程接口,是一些预先定义的函数

Unity引擎提供了丰富的组件和类库,为开发者提供了非常大的便利,苏联从、掌握和使用这些API对于游戏开发效率提高很重要

Ø  注意:

1.组件都不能now,如果需要为物体添加组件,调用物体的AddComponent方法

2.所有附加到物体上的类,必须继承自Component

Component

Ø  常用属性:gameObject  transform colliderrenderer

Ø  常用方法: GetComponentGetComponentInChildren GetComponentInparent

Ø  小练习:

  方法    (调用方法的是游戏对象,不是类)

       private void Start()

       {           //this 表示该游戏对象

           //附加到2个物体中,问:获取到的是哪个物体的位置?

             Vector3 pos = this.transform.position;

           Debug.Lod(pos);//?先获取第1个对象的位置,再获取第2个对象的位置

        }

       private void OnGUI()

        {

           if(GUILayout.Button("GetComponent"))//运行时在Unity生成一个按钮,点击运行1次下边代码

           {  //GetComponent : 在当前物体中根据类型查找组件

               //修改当前物体颜色     脚本对象-->组件对象-->属性

          this.GetComponent<MeshRenderer>().material.color = color.red

               //结论:获取1个组件引用,即可获取其他类型组件引用

           }

            if(GUILayout.Button("GetComponent"))

           {                //在当前物体中查找所有组件

               Var all Component = this.GetComponents<Component>();

               foreach(var item in allComponent)

               {

                    Debug.Lod(item);

               }

               var allScript = this.GetComponents<MonoBehaviour>();//查找所有脚本。脚本都继承于MonoBehaviour类,找儿子就写到父亲

               foreach(var item in allScript)

               {

                    Debug.Lod(item);

               }

           }

        if(GUILayout.Button("GetComponent"))

          {  //从自身开始查找 所有后代物体指定类型组件

           var renderer = GetComponentInChildern<MeshRenderer>();

           //从自身开始查找 所有先辈物体指定类型组件

           var renderer = GetComponentInParent<MeshRenderer>();

           }

        }

Transform

Ø  简述:提供设置位置方位+/(在、移动,自传,围绕旋转,注释旋转)

查找(根据名字,索引找子物体,父,根物体)功能。

Ø  Transform组件的成员变量

Ø  Transform组件的成员函数

Ø  应用示例:

1.  向前方移动

2.  绕自身坐标轴y轴旋转

3.  绕世界坐标轴的y轴旋转

4.  使相机观察方向跟随物体移动

Ø  课堂小练习:

public classTransformDemo02 : MonoBehaviour

{

    public Transform target;

    public string childName;

    private void OnGUI()

    {

        #region 位置、方位相关

        //相对于世界坐标系的坐标

        Vector3 worldPos = transform.position;

        //相对于父物体的坐标[编译器中显示]

        Vector3 localPos =transform.localPosition;

        //相对于父物体的缩放比例[编译器中显示]

        Vector3 localScale =transform.localScale;

        //理解为:相对于模型的缩放比例(父物体.localScale * 当前物体.localScale)

        Vector3 lossyScale =transform.lossyScale;

        if (GUILayout.Button("向前移动1m(自身)"))

        {

            //沿自身坐标系移动

            transform.Translate(0, 0,1);//translate:调动

        }

        if (GUILayout.Button("向前移动1m(世界)"))//每一帧执行一次

        {

            //沿世界坐标系移动

            transform.Translate(0, 0, 1,Space.World);

        }

        if (GUILayout.RepeatButton("沿y轴旋转1度(自身)"))

        {

            //沿自身坐标系旋转

            transform.Rotate(0, 1, 0);

        }

        if (GUILayout.RepeatButton("沿y轴旋转1度(世界)"))

        {

            //沿世界坐标系旋转

            transform.Rotate(0, 1, 0,Space.World);

        }

        if(GUILayout.RepeatButton("LookAt"))

        {

            //注视旋转(z轴指向目标物体位置)

            transform.LookAt(target);

        }

        if(GUILayout.RepeatButton("RotateAround"))

        {

            //围绕旋转(围绕的点,围绕的轴,旋转角度)

           transform.RotateAround(target.position, Vector3.right, 1);

        }

        #endregion

 

        #region 查找

        if (GUILayout.Button("根据名字查找子物体"))

        {

            //需求:获取某个子物体的MeshRenderer组件

            //名称 --> 变换组件 --> 其他组件

            Transform tf =transform.Find(childName);  //只能查找孩子

           tf.GetComponent<MeshRenderer>().material.color = Color.red;

            //缺点:限制物体层级关系

            //建议:通过方法递归查找某个后代物体

            //transform.Find("子物体/子物体")

        }

        if (GUILayout.Button("根据索引查找子物体"))//通过索引查找,索引的顺序与Unity面板顺序一致

        {

            //transform.childCount 子物体数量

            //需求:获取所有子物体(第一代)

            for (int i = 0; i <transform.childCount; i++)

            {

                Transform childTF = transform.GetChild(i);

            }

        }

        //获取父物体

        Transform parentTF =transform.parent;

        //设置父物体

        //transform.SetParent(父物体变换组件);

        //获取根物体    根物体:指层级最顶层的物体

        Transform root = transform.root;

        #endregion

    }

}

 

GameObject

简述:提供了对物体操作(创建,激活、禁用,查找(标签))功能

注意:小写的是对象引用(gameobject)大写的是类名(GameObject)

小练习:

   public class GameObjectDemo03 : MonoBehaviour

{

    //变量:

    //activeInHierarchy 物体在场景中激活状态

    //activeSelf  物体自身激活状态

    //如果父物体被禁用,子物体在场景中也被禁用。

    //此时,子物体activeInHierarchy为false,activeSelf为true

    public GameObject targetGO;

    private void OnGUI()

    {

        //需求:禁用/启用物体

        if (GUILayout.Button("禁用/启用物体"))

        {

           targetGO.SetActive(!targetGO.activeInHierarchy);

        }

        //需求:创建红色的聚光灯

        if (GUILayout.Button("创建红色的聚光灯"))

        {

            GameObject go = newGameObject("MyLight");

            Light light =go.AddComponent<Light>();

            light.color = Color.red;

            light.type = LightType.Spot;

        }

        if (GUILayout.Button("创建红色的聚光灯"))

        {

            //场景中物体往往过多,所以 慎用  。

            //GameObject go01 =GameObject.Find("物体名称");

          

            //根据标签查找单一物体

            GameObject playerGO = GameObject.FindWithTag("Player");

            //查找使用指定标签的所有物体

            GameObject[] allEnemy =GameObject.FindGameObjectsWithTag("Enemy");

        }

    }

Object类(提供了 功能)

简述:Unity中能用的东西都叫object

 

归纳4个常用类,查找方法

 Component类: 查找组件(父物体、根物体、根据名称、索引查找子物体)

    GetComponent:当前物体根据类型找组件 

       this.GetComponent<MeshRenderer>().material.color= Color.red;

    GetComponents:当前物体中查找所有组件

        varallComponent = this.GetComponents<Component>();

    GetComponentChildern:从自身开始找所有后代物体指定类型组件

        var rendererChildern =this.GetComponentChildern<MeshRenderer>();

    GetComponentParent:自身开始查找所有先辈指定类型组件

   varrendererParent = this.GetComponentParent<MeshRenderer>();

Transform类: 查找变换组件(父物体、根物体、根据名称、索引查找子物体)

根据名字查找物体:

   transform.Find("子物体/子物体")

          Transform tf = transform.Find(childName);//只能查找孩子

根据索引查找子物体:

   Transform childTF02 = transform.GetChild(0); //根据索引

Transform[] childTF = newTransform[transform.childCount];  //获取所有     

    for(inti=0;i<transform.childCount;i++)

    {

       childTF = transform.GetChild(i);

    }

    查找物体

    Transform parentTF = transform.parent;

    查找物体

    Transform root = transform.root;

GameObject类:通过标签、名字查找游戏对象, GetComponent查找组件(当前物体、先辈、后代)

    根据标签查找单一物体:

    GameObject playerGo = GameObject.FindWithTag("player");

    查找使用指定标签所有物体:

    GameObject[] allEnemy = GameObject.FindGameObjectsWithTag("Enemy");

object类:  查找对象(组件 物体) 根据类型

     //获取指定类型所有对象

            //FindObjectsOfType<Enemy>()

            FindObjectsOfType<Enemy>();

      //获取指定类型一个对象

            //FindObjectOfType<Player>()

 

Time

简述:ity中可以通过Time类用来获取时间有关的信息,可以用来计算帧速率调整时间流逝速度等功能

恒定的速度: 如果在渲染帧运动,必须在速度上乘以每帧间隔,以得到恒定速度

例如: transform.Rotate(0,Time.deltaTime*speed,0)

时间缩放(整体游戏进度):

实质:影响 fixedUpdete 执行频率

结论:不影响 Update 执行频率(不影响渲染) 影响 Time.deltaTime

游戏暂停为0 游戏继续为 1 游戏快进为 2 游戏慢动作 0.5

Time.TimeScale=值?

 

 

Time类的成员变量:

预制件Prefab (倒计时练习)

Ø  一种资源类型,可以多次在场景进行实例

Ø  优点:对预设制件的修改,可以同步到所有实例,从而提高开发效率

Ø  如果单独修改实例的属性值,则改值不在随预制件变化

Ø  Select键:通过预制件实例选择对应预制件

Ø  Revert键:放弃实例属性值,还原预制件属性值

Ø  Apply键:将某一实例的修改应用到所有实例中

Ø  需求:使用Text制作倒计时预制件,从02:00开始,最后10秒字体为红色,时间为00:00后停止计时

 //**********************方案一******************************

//重点:①定义下次修改时间②当到达时间③执行逻辑④在当前时间上累加一秒

//语法重点:  Time.time(游戏开始当前的真实时间)

//            string.Format("占位符",变量)(在Unity中用占位符需要使用)

private Text textTimer;

     publicint num = 120;

     voidStart()

     {

        textTimer = GetComponent<Text>();

     }

     voidUpdate()

     {

        Timer();

     }

    private float nextTimer = 1;

     void Timer()

     {

         if(nextTimer <= Time.time)

         {

            num--;

            textTimer.text = string.Format ("{0:d2},{1:d2}", num / 60, num% 60);

            nextTimer = Time.time + 1;

         }

         if(num <= 10)

         {

            textTimer.color = Color.red;

         }

     }

//**********************方案二******************************

//重点:①定义用于记录累加时间的变量②累加每帧间隔③当时间到了④执行逻辑⑤清零记录累加时间的变量

//语法重点:   Time.deltaTime(上一帧所有的时间 、也就是每帧间隔时间) 

private int num = 120;

private Text textTimer;

private float newTimer;

public float intervalTimer=1;

void Start()

{

   textTimer = GetComponent<Text>();

}

 

void Update()

{

   Timer();

}

 

void Timer()

{

   newTimer += Time.deltaTime;

    if(newTimer >= intervalTimer)

    {

       num--;

       textTimer.text=string.Format("{0:d2}:{1:d2}", num / 60, num %60);

       newTimer = 0;

    }

}  

//**********************方案三******************************

//语法重点: 【重复调用】   InvokeRepeating(“方法名称”,开始执行时间,间隔)

//           【延迟调用】   Invoke("方法名称",开始执行时间)

//           【取消调用】   CancelInvoke(“方法名”) 

privateText textTimer;

privatefloat num = 120;

publicfloat intervalTimer=1;

publicfloat startTimer = 1;

voidStart()

{

 textTimer =GetComponent<Text>();

 InvokeRepeating("Timer", 1, 1);

}

 

void Timer()

{

    num--;

    textTimer.text =string.Format("{0}:{1}", num / 60, num % 60);

    if (num == 0)

    {

        CancelInvoke("Timer");

    }

}

Random类

简述:可以用来生成随机数,随机点或者旋转

Random类的成员变量:

Mathf类

简述:提供了常用的数学运算

Mathf类的变量

Mathf类的常用方法

Coroutine协同程序

简述:也称为同程序或者协程,协同程序可以喝主程序并行运行,和多线程有些类似但是在任意指定时刻只会有一个协同程序在运行,别的程序则会挂起。协同程序可以用来实现让一段程序等待一段儿时间后继续运行的效果。

例如:执行步骤1 ,等待3秒;执行步骤2,等待某个条件为true;执行不会走。。。

Unity里和协同程序有关的函数有:

注意:在c#中,协同函数的返回类型必须为IEnumerator,yield要用yieldreturn来替代,并且启动协同程序右StartCoroutine函数

例程:

测试结果为:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值