You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity/C# 如何实现可设置任意int变量的通用setResource函数

需求可行性说明

你最初构思的参数为int resource, int amount的方法无法实现需求:Java是值传递,调用player.setResource(player.money, 100)时,传入的第一个参数仅为money的当前数值,方法内部无法获知该数值对应Player类的哪个成员字段,自然无法完成赋值。

推荐实现方案

方案1:枚举标记资源类型(最适合小型项目,类型安全)

这是最稳妥的实现方式,编译期即可校验参数合法性,无额外性能开销:

  1. 首先定义资源类型枚举:
public enum ResourceType {
    // 按实际需求扩展所有资源类型
    MONEY, COAL, WOOD, FOOD
}
  1. 编写Player类的对应方法:
public class Player {
    private int money;
    private int coal;
    private int wood;
    private int food;

    public void setResource(ResourceType resourceType, int amount) {
        switch (resourceType) {
            case MONEY -> this.money = amount;
            case COAL -> this.coal = amount;
            case WOOD -> this.wood = amount;
            case FOOD -> this.food = amount;
            default -> throw new IllegalArgumentException("不支持的资源类型");
        }
    }

    // 可选配套取值方法
    public int getResource(ResourceType resourceType) {
        return switch (resourceType) {
            case MONEY -> this.money;
            case COAL -> this.coal;
            case WOOD -> this.wood;
            case FOOD -> this.food;
            default -> throw new IllegalArgumentException("不支持的资源类型");
        };
    }
}
  1. 调用方式:
player.setResource(ResourceType.MONEY, 100);
player.setResource(ResourceType.COAL, 20);

方案2:Map存储资源(扩展灵活,无需新增字段)

如果后续需要频繁新增资源类型,不需要类型强校验的话可以用这个方案:

public class Player {
    // 默认值设为0,避免空指针
    private final Map<String, Integer> resources = new HashMap<>();

    public void setResource(String resourceName, int amount) {
        resources.put(resourceName, amount);
    }

    public int getResource(String resourceName) {
        return resources.getOrDefault(resourceName, 0);
    }
}

调用方式:

player.setResource("money", 100);
player.setResource("coal", 20);

不推荐方案:反射赋值

也可以通过反射直接给字段赋值,但存在字段名拼写错误运行时报错、性能开销大的问题,仅做参考:

public void setResource(String fieldName, int amount) {
    try {
        Field field = Player.class.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.setInt(this, amount);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new RuntimeException("资源字段不存在", e);
    }
}

内容的提问来源于stack exchange,提问作者idzczakp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:45:08