Unity的C#編程教程_50_方法挑戰:改變遊戲對象的顏色

Challenge: Pass the Object with Color

  • 任務說明:
    • 設計一個改變方塊顏色的方法
    • 當按下空格鍵的時候調用該方法,改變方塊的顏色
    • 該方法需有兩個傳入參數:遊戲對象,目標顏色
    • 該方法無返回值

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
​
public class ChangeColor : MonoBehaviour
{
​
public GameObject cube; // 定義一個 cube
public Color targetColor; // 定義一個顏色
​
// Start is called before the first frame update
void Start()
{
targetColor = Color.red; // 初始化,將目標顏色設定為紅色
}
​
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) // 檢測按下空格鍵
{
Change(cube, targetColor); // 調用改變顏色的方法,傳入遊戲對象和目標顏色
}
}
​
private void Change(GameObject a,Color targetColor) // 該方法需要 2 個傳入參數
{
a.GetComponent().material.color = targetColor; // 改變對象顏色
}
}
​把該腳本可以掛載到 Main Camera 上,在窗口新建一個 cube,然後用拖動賦值的方法,把腳本下的 Cube 對象進行賦值,執行程式後,Target Color 初始化為紅色,按下空格鍵後,遊戲窗口中的方塊變為紅色。

Tags: