提示:这个 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 updatevoidStart(){
cube.GetComponent<Renderer>().material.color = redColor;// 首先使用GetComponent获取游戏对象下面挂载的组件// 这里我们需要的是 Renderer 组件,用于控制游戏对象的材质// 在这个组件下有个 material 材料属性// 材料属性下有子属性:颜色}// Update is called once per framevoidUpdate(){if(Input.GetKeyDown(KeyCode.Space))// 判断按下空格键{
score +=10;// 加十分if(score >=60)// 如果分数达到 60 分{
cube.GetComponent<Renderer>().material.color = Color.blue;// 变化颜色,这里就直接用了 Color.blue 变成蓝色}}}}