U3D脚本开发基础(转载)

转注:《Unity 5.x 从入门到精通》上有更详细的说明。

1.MonoBehaviour类,定义了对各种特定事件的脚本响应函数。这些函数均以On做开头。

 

2.U3D中常用的组件及对应变量名如下:

 Transform(transform),Rigidbody(rigidbody),Renderer(renderer),Light(light),Camera(camera),Collider(collider),Animation(animation),Audio(audio)。

 如果游戏对象上不存在某个组件,那么其对应值为null。

 若要访问自定义组件,通过以下几个函数:

       GetComponent; //得到组件

        GetComponents;//得到组件列表

        GetComponentInChildren; //得到对象子物体的组件

        GetComponentsInChildren;//得到对象子物体的组件列表

3.除了获得组件,还需要访问对象。可以通过名称查找或标签查找来获得。

       GameObject.Find("name");

        GameObject.FindWithTag("Tag");

常用脚本API:

1.Transform组件决定了游戏对象的位置,方向和缩放比例。游戏中设置玩家位置,相机观察角度都要和Transform组件打交道。

2.Time类,可以计算帧速率,调整时间流逝速度等等。

3.Random类,可以用来生成随机数,随机点或旋转。

4.Mathf类,提供了常用的数学运算。

5.Coroutine协程。协程可以和主程序并行运行,和多线程类似,但某个时刻只能有一个协程在运行,别的协程挂起。可以实现一段程序等待一段时间后,继续执行的效果。

StartCoroutine() //启动一个协程

StopCoroutine()  //终止一个协程

StopAllCoroutines()//终止所有协程

WaitForFixedUpdate()//等待直到下一次FixedUpdate调用

WaitForSeconds() //等待若干秒

在C#中,其返回类型必须为IEnumerator。如以下:

using UnityEngine;
using System.Collections;

public class backg : MonoBehaviour
{
    // Use this for initialization
    IEnumerator Start()
    {
        print("Starting:" + Time.time);
        yield return StartCoroutine(WaitAndPrint());
        print("Done:" + Time.time);

    }

    IEnumerator WaitAndPrint()
    {
        yield return new WaitForSeconds(3f);
        print("WaitAndPrint:" + Time.time);
    }

}

原文地址:http://www.cnblogs.com/hometown/p/3757685.html

猜你喜欢

转载自www.cnblogs.com/BeforeEnd/p/10316638.html