Unity的几个常用的基本的类,即API

预制件的使用会提高开发的效率,如下箭头1所指即为预制件,箭头2 为该预制件的实例

 

一、Component

1、Component 类继承自上面的父类,则父类中的方法在Component类,及继承自Component类的子子类中仍然可以使用。

public class ComponentDemo : MonoBehaviour 
{
    private void OnGUI()
    {
        if (GUILayout.Button("按钮"))
        {
            print("Ok,YOU have click this button");
        }
    }

}

2、 GetComponent<>() 为获取当前物体的某一组件

public class ComponentDemo : MonoBehaviour 
{
    private void OnGUI()
    {
        if (GUILayout.Button("按钮"))
        {
            print("Ok,YOU have click this button");
            this.transform.position = new Vector3(17, 0, 13);

            // this指当前的脚本(即ComponentDemo),也可以省略。
            // GetComponent<>()为获取当前物体的某一个组件,即在一个脚本中使用另一个脚本的内容
            // MeshRenderer 为要使用的组件,material.color为该组件中的属性
            this.GetComponent<MeshRenderer>().material.color = Color.red;
        }
    }
}

3、GetComponents<Component>() :获取当前物体的所有组件

public class ComponentDemo : MonoBehaviour 
{
    private void OnGUI()
    {
        if (GUILayout.Button("GetComponents"))
        {
            // 获取当前物体的所有组件
            var allComponent = this.GetComponents<Component>();
            //将获取到的组件输出显示在控制台上
            foreach(var x in allComponent)
            {
                print(x.GetType());
            }
        }
    }
}

二、Transform

(一)、属性

1、position :变换的世界坐标

2、localPosition:子物体变换的位置相对于父物体的变换,指的是子物体相对于父物体的坐标。

    private void OnGUI()
    {
        if (GUILayout.Button("GetComponents"))
        {
            // 物体相对于世界坐标系原点的位置
            Vector3 worldpos= this.transform.position;
            // 物体相对父物体轴心点的位置
            Vector3 localpos = this.transform.localPosition;
            print(worldpos);
            print(localpos);
        }
    }

类似的还有 rotation、localPositionlocalScale

(二)、方法

1、   Rotate ———— 旋转

(1)、该脚本设置的绕Y周旋转指定角度的用法

public class ComponentDemo : MonoBehaviour 
{
    private void OnGUI()
    {
        if (GUILayout.Button("Rotate01"))
        {
            //沿自身坐标系Y轴旋转60度
            this.transform.Rotate(0, 60, 0);
        }
        if (GUILayout.Button("Rotate02"))
        {
            //沿世界坐标系Y轴旋转30度
            this.transform.Rotate(0, 30, 0, Space.World);
        }
    }
}

 (2)、旋转的其它用法总结:

当transform.Rotate(a,b,c) 函数有三个参数时: a表示旋转轴,绕哪个轴旋转;b表示旋转速度,一般用角度来表示;
c表示绕自身坐标系旋转还是世界坐标系(一般缺省为绕自身Space.Self,绕世界坐标系时需要设置为Space.World)
transform.Rotate(d,e) 函数也可以只有两个参数,第一个参数表示旋转轴和旋转角度,为矢量;第二个参数e为所在的坐标系,可以缺省。

1、在不声明public变量的情况下,直接使用旋转角度的几种表示方式,在Update ()函数中:
//方法一:Vector3.up表示沿y轴正方向。物体在自身坐标系下以y轴为中心,每帧旋转10度。
transform.Rotate(Vector3.up,10,Space.Self);

//方法二:物体在自身坐标系下以y轴为中心,每帧旋转10度。
transform.Rotate(Vector3.up*10,Space.Self);

//方法三:物体在自身坐标系下,以z轴为旋转轴,每帧旋转10度。
transform.Rotate(new Vector3(0, 0, 1), 10);
//new Vector3(0, 0, 1)表示声明一个旋转轴

// 旋转的速度也可以用浮点数来表示,如下:transform.Rotate(Vector3.up,30.0f,Space.Self);

2、通过在 Start() 方法前,声明公共变量(public)的方式。public方式的变量能在检视器中看到并修改,无需在脚本和编辑器中来回切换。
//只需要将以上的具体角度数值换成变量rotateAngle即可实现在inspector中进行修改
public class selfRotate : MonoBehaviour {
    public int rotateAngle = 10;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        transform.Rotate(Vector3.up , rotateAngle);
    }
}

//注意:游戏是在帧率(帧/秒)下运行的,帧率是取决于硬件和它运行压力,这样在性能好的机器上帧率快,
//而在性能差的机器上帧率慢,从而导致不可预知的结果。通常的办法是,当需要按每帧执行一个动作时,
//都乘上 Time.deltaTime。如下所示:
transform.Rotate(Vector3.up , 10*Time.deltaTime);
//或者
transform.Rotate(Vector3.up , rotateAngle*Time.deltaTime);

2、  Translate ———— 移动

 (1)、将该脚本挂载到某一物体上,运行时效果如下图

public class ComponentDemo : MonoBehaviour 
{
    private void OnGUI()
    {
        if (GUILayout.Button("Translate01"))
        {
            //沿自身坐标系X轴平移0.8米
            this.transform.Translate(0.8f, 0, 0);
        }
        if (GUILayout.Button("Translate02"))
        {
            //沿世界坐标系X轴平移0.8米
            this.transform.Translate(0.8f, 0, 0, Space.World);
        }
    }
}

  

 (2)、平移的其它用法总结:

平移与上面的旋转类似,只是使用的函数为:transform.Translate(g,h) 。其中的该函数具有二个参数:
g表示物体移动的速度,它是一个矢量,具有方向和大小;h表示在哪个坐标系下,缺省时指的是物体自身的坐标系Space.Self。

物体在世界坐标系下每帧沿着y轴正方向移动moveSpeed。速度的单位为:米/秒
//方法一:
public class selfRotate : MonoBehaviour {
    public float moveSpeed = 1.0f;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        transform.Translate(Vector3.up * moveSpeed*Time.deltaTime,Space.World);
    }
}

// 方法二:
public class selfRotate : MonoBehaviour {
    public float moveSpeed = 1.0f;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        transform.Translate(new Vector3(0,1,0) * moveSpeed*Time.deltaTime,Space.World);
    }
}

3、 RotateAround ———— 围绕旋转

public class ComponentDemo : MonoBehaviour 
{
    private void OnGUI()
    {
        if (GUILayout.RepeatButton("RotateAround")) //按住鼠标不动会连续的每帧运动一次
        {
            // 以世界坐标零点为中心,Y轴为旋转轴,旋转2度
            this.transform.RotateAround(Vector3.zero, Vector3.up, 2);
        }
    }
}

4、其它常用功能

// 获取根物体
Transform rootTF = transform.root;
// 获取父物体
Transform parentTF = transform.parent;
// 设置父物体为theParent
transform.SetParent(theParent);
// 查找子物体(不能查找孙子),查找结果是变换组件
Transform childTF = transform.Find("NameOfTheChild");
// 查找子子物体
Transform chchildTF = transform.Find("NameOfTheChild/SonOfTheChild");

三、GameObject

1、场景中(即:Hierarchy 面板中)的所有实体都是GameObject

2、属性及用法

 

// 在场景中物体的实际激活状态
bool gameState = gameObject.activeInHierarchy;
// 物体自身的激活状态(物体在Inspector面板中的状态)
bool selfState = gameObject.activeSelf;
// 设置物体禁用/启用
gameObject.SetActive(true);

// 通过代码创建一个物体
GameObject theGO = new GameObject();
// 添加光照的组件
Light light = theGO.AddComponent<Light>();
light.color = Color.red;
light.type = LightType.Point;

四、Time

1、time:指从该帧开始到当前所用的时间,指游戏运行的时间

2、deltaTime:每帧消耗的时间。常用在Update函数中

void Update () {
    // 每渲染帧执行一次,旋转一度
    // 旋转速度*每帧消耗时间,可以保证旋转速度不受机器性能和渲染影响
    transform.Rotate(0, 1*Time.deltaTime, 0);
}

注意:在 FixedUpdate() 函数中,速度就不需要乘以 Time.deltaTime ,因为其时间是固定的,与渲染无关。

3、timeScale:时间尺度,用来控制物体运动的暂停和停止。

注意:Update 函数渲染场景时执行,每渲染帧执行一次(注:渲染只是与硬件有关),不受 timeScale 的影响。但是当物体的速度乘以 Time.deltaTime 后,就会因为 Time.deltaTime 受到 timeScale 的约束,而使得 Update 函数也看起来是受 timeScale 的影响;FixedUpdate() 函数是固定时间执行一次(默认的是0.02s),其与渲染无关,会受到 timeScale 的影响。

(1)、点击暂停和开始来让物体停止/开始运动

public class TimeDemo : MonoBehaviour 
{
    private void FixedUpdate()
    {
        transform.Rotate(0, 100, 0);
    }
    private void OnGUI()
    {
        if (GUILayout.Button("Stop"))
        {
            Time.timeScale = 0;
        }
        if (GUILayout.Button("Start"))
        {
            Time.timeScale = 1;
        }
    }
}

以上代码在Unity中的效果如下图:

  

(2)、点击Stop之后部分物体停止运动,其他物体不受影响。此时要在Update函数中来进行操作:将速度乘以 unscaledDeltaTime ,即可让物体不受 timeScale 的影响

private void Update()
{
    transform.Rotate(0, 100*Time.unscaledDeltaTime, 0);
}
private void OnGUI()
{
    if (GUILayout.Button("Stop"))
    {
        Time.timeScale = 0;
    }
    if (GUILayout.Button("Start"))
    {
        Time.timeScale = 1;
    }
}

【注】:实例—计时器:设置一个定时器倒计时2分钟,到最后10s钟的时候,用红色的字体来显示。具体流程、代码方法及效果如下:

(1)、创建Text,并将其名称修改的有意义。调整好文本显示的位置如下图

     

 (2)两种代码实现的方法如下,若要使用 Text,则必须包含命名空间:UnityEngine.UI

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TimeDemo : MonoBehaviour 
{
    private Text textTimer;
    private int  nextTime=1; //指定的时间间隔
    public int second = 120;
    private void Start()
    {
        // 获取同一物体其它类型的组件(脚本)
        textTimer = GetComponent<Text>();

        //方法三的调用是在Start函数中使用重复调用来实现
        InvokeRepeating("Timer03", 1, 1); //重复调用Timer03
    }
   private void Update()
    {
        Timer01(); //调用方法一
        Timer02(); //调用方法二
    }

    //******************* 方法一 *********************************
    private void Timer01()
    {
        //在Update每帧执行的方法中,个别语句实现指定间隔执行一次
        if (Time.time >= nextTime && second > 0)
        {
            second--;
            // 在字符串中插入变量,就用 string.Format,其返回一个字符串。d2是设置该变量的格式:用0来填充
            textTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
            if (second < 10)
            {
                textTimer.color = Color.red;
            }
            nextTime += 1;
        }
    }

    //******************* 方法二 *********************************
    private float totalTime=0;
    void Timer02()
    {
        totalTime += Time.deltaTime;//累加每帧的间隔
        if (totalTime >= 1 && second > 0)  // 直到时间为1s
        {
            second--;
            textTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
            if (second < 10)
            {
                textTimer.color = Color.red;
            }
            totalTime = 0;
        }
    }

    //******************* 方法三 *********************************
    private void Timer03()
    {
        second--;
        textTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
        if (second < 10)
        {
            textTimer.color = Color.red;
        }
        if (second <= 0)
        {
            //取消调用
            CancelInvoke("Timer03");
        }
    }
}

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐