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<MeshRenderer>().material.color = targetColor; // 改变对象颜色
}
}
把该脚本可以挂载到 Main Camera 上,在窗口新建一个 cube,然后用拖动赋值的方法,把脚本下的 Cube 对象进行赋值,执行程序后,Target Color 初始化为红色,按下空格键后,游戏窗口中的方块变为红色。