天天看點

【4.UI和排程器】5.元件化開發

作者:青少年程式設計ABC

5.元件化開發

5.1什麼是元件

元件是指遊戲對象中各個可以更新的部件。通過給遊戲對象添加各種元件,遊戲對象就具有了各種各樣的功能,比如:腳本也是一種元件,給遊戲對象挂載腳本,遊戲對象就可以執行腳本中的程式。

對于 Unity 對象,我們可以在其上面添加各種設定(相當于挂載元件)來豐富其功能。比如:要讓對象具有實體特性,可以挂載 Rigidbody 元件;要讓它發出聲音,可以挂載 AudioSource 元件;要讓它具有特殊的功能,可以挂載腳本元件。

5.2 Transform 元件

在 Unity 中,用于管理對象坐标與旋轉的元件是 Transform 元件。該元件相當于方向盤,負責提供坐标資料及旋轉和移動等功能。比如在前面的腳本中,car.transform.position.x 就是通路小車對象上挂載的 Transform 元件所持有的坐标(position)資訊。一般情況下,除了 Transform 元件外,其它元件幾乎都不支援這種寫法。

5.3 通路元件

如何通路元件?在前面的程式中出現的 GetComponent 方法會傳回相應的元件。

如:

需要通路 AudioSound 元件可用調用:

GetComponent<AudioSound>()           

需要通路 Text 元件可用調用:

GetComponent<Text>()           

在通路 Transform 元件時也可以調用:

GetComponent<Transform >()           

實際上直接使用 transform 就相當于上面的代碼。

此外,我們編寫的腳本也屬于元件,也可以通過 GetComponent 來調用。

通過 GetComponent 方法調用腳本的方法:

  1. 用 Find 方法找到對象;
  2. 用 GetComponent 方法擷取對象上挂載的腳本元件;
  3. 通路腳本中的資料或調用腳本中的方法;

示例:

将小車的速度顯示到 Text 中,實作該功能就需要修改排程器腳本,在排程器腳本中,通路小車上挂載的控制器腳本,通路控制器腳本的 speed 成員變量即可。

控制器腳本增加如下代碼用于擷取速度資料:

public float GetSpeed()
{
    return speed;
}           

排程器腳本修改如下:

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


public class Director : MonoBehaviour
{
    GameObject car;
    GameObject flag;
    GameObject distance;
    // Start is called before the first frame update
    void Start()
    {
        car = GameObject.Find("car");
        flag = GameObject.Find("flag");
        distance = GameObject.Find("Distance");
    }

    // Update is called once per frame
    void Update()
    {        
        float XCar = car.transform.position.x;
        float XFlag = flag.transform.position.x;
        float length = XFlag - XCar;


        if (length <= 0)
        {
            this.distance.GetComponent<Text>().text = "遊戲結束";
        }
        else
        {
            this.distance.GetComponent<Text>().text = "距離目标:" +
             length.ToString("f3") + "米,行駛速度:" + 
             car.GetComponent<CarController>().GetSpeed().ToString("f3") + "m/s";
        }
    }
}           

在上面的代碼中,我們要擷取小車的控制器腳本,使用:

car.GetComponent<CarController>()           

來擷取,然後調用控制器腳本中增加的方法 GetSpeed 來擷取速度值。

繼續閱讀