Unity的C#编程教程_18_Variables 挑战 4 计算平均伤害
- 2020 年 8 月 1 日
- AI
- C/C++/C#
- 这里进行 5 次 攻击
- 攻击伤害随机
- 计算平均伤害
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageCalculator : MonoBehaviour
{
public float hit1, hit2, hit3, hit4, hit5;
// 可以直接用逗号创建类似的变量
// Start is called before the first frame update
void Start()
{
hit1 = Random.Range(0f, 100f);
hit2 = Random.Range(0f, 100f);
hit3 = Random.Range(0f, 100f);
hit4 = Random.Range(0f, 100f);
hit5 = Random.Range(0f, 100f);
float average = (hit1 + hit2 + hit3 + hit4 + hit5) / 5;
// 不要忘记括号
average = Mathf.Round(average * 100f) / 100f;
// 保留两位小数
// 先乘以 100 然后取整,然后再除以 100
Debug.Log("Average Damage: " + average);
}
// Update is called once per frame
void Update()
{
}
}
- 把脚本挂载到 Main Camera 下面
- 运行游戏后,可以看到随机数生成了,然后在 console 里面可以看到计算的平均伤害
- 另外,以上脚本中有个涉及保留n位小数的小技巧