Unity的C#編程教程_18_Variables 挑戰 4 計算平均傷害

  • 這裡進行 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位小數的小技巧
Tags: