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<MeshRenderer>().material.color = targetColor; // 改变对象颜色
    }
}

把该脚本可以挂载到 Main Camera 上,在窗口新建一个 cube,然后用拖动赋值的方法,把脚本下的 Cube 对象进行赋值,执行程序后,Target Color 初始化为红色,按下空格键后,游戏窗口中的方块变为红色。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值