Unity的C#编程教程_48_带参数的方法

2. Method Parameters

  • 我们使用方法,来创建模块化的编程,这样程序看起来简洁,思路也更为清晰。而不是把所有程序都直接堆进 Update 里面去

  • 比如我们游戏中的各种典型场景,可以分别放入对应的方法中

    • 攻击场景:计算伤害,造成扣血
    • 吃 Buff 的场景:提升某种能力
  • 这样做的好处是,如果哪一块代码出了问题,那么我们可以很好去定位

  • 而 Update 中,最好只放监控程序,即收集游戏运行中的各种指标和数据,而具体的指标运算和反馈游戏效果,可以放到专门的方法中执行

  • 另外,方法名通常首字母大写,长的名字可以配合驼峰法则

  • 即然方法是用来做特定计算的,那如何传入计算数据,计算完成后又如何读取数据呢?

传入参数:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Sum(5, 4); // 调用方法的时候,传入与指定类型即个数相符合的参数
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void Sum(int a,int b) // 设定需要传入参数的个数和类型
    {
        Debug.Log(a + b); // 在方法的语句中运用这些参数进行运算
    }
}

以此设计一个伤害扣血方法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{

    public int health;
    public int hit;

    // Start is called before the first frame update
    void Start()
    {
        health = 100; // 游戏初始化的时候,角色 100 点血量
        hit = 10; // 每次攻击扣血 10 点
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // 假设按下空格键就是受到了攻击
        {
            Damage(hit); // 调用方法计算攻击伤害
        }
    }

    private void Damage(int getHit) // 设定需要传入参数为伤害,类型 int
    {
        health -= getHit; // 计算扣血后的血量
        if (health > 0)
        {
            Debug.Log("Health: " + health);
        }
        else
        {
            health = 0; // 如果血量低于 0,则把血量设置为 0
            Debug.Log("Health: " + health);
            Destroy(this.gameObject); // 血量扣到 0,则在 unity 中销毁这个游戏对象
        }
    }
}

把这个脚本挂载到一个游戏对象上(比如一个 cube 上面),当你不断按下空格键扣血到 0,这个游戏对象就会被销毁。

其实在方法中,我们不仅仅可以传入 int 类型的数字,还可以传入字符串,甚至直接传入游戏对象,然后在方法里面进行运算和操作,比如上面的例子,我们可以直接把 cube 的游戏对象传到方法中,然后在方法中进行对应操作。

Tags: