Unity的C#編程教程_26_if 條件語句挑戰4

  • 在遊戲里創建一個 cube,確認初始位置為 0,0,0
  • 任務:最初 cube 為紅色,每次按下空格加十分,達到60分以後,cube 變為藍色
  • 提示:這個 cube 也是個變數,類型為 GameObject,假設我們在 Main Camera 下面掛載的腳本中設置了一個 public GameObject cube 變數,那我們就可以 Unity 中用拖拽的方式進行賦值

  • 創建一個腳本掛載在 Main Camera 下,打開添加 GameObject 變數,然後在 Unity 中把場景中的 cube 拖拽進行賦值
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player : MonoBehaviour
{

    public GameObject cube;
    // 創建變數後,到 Unity 中拖拽賦值

    private Color redColor = Color.red; // 設置個顏色變數,其實也可以直接用
    public int score = 0;
    // 創建變數存儲分數,使用 public 可以在 unity 中看到分數變化


    // Start is called before the first frame update
    void Start()
    {
        cube.GetComponent<Renderer>().material.color = redColor;
        // 首先使用GetComponent獲取遊戲對象下面掛載的組件
        // 這裡我們需要的是 Renderer 組件,用於控制遊戲對象的材質
        // 在這個組件下有個 material 材料屬性
        // 材料屬性下有子屬性:顏色

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))// 判斷按下空格鍵
        {
            score += 10;// 加十分

            if (score >= 60)// 如果分數達到 60 分
            {
                cube.GetComponent<Renderer>().material.color = Color.blue;
                // 變化顏色,這裡就直接用了 Color.blue 變成藍色
            }
            
        }
    }
}

Tags: