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

如何获取Unity自定义类Buyables的布尔成员hasBought的值并完成赋值

实现方法

首先你需要在存储Buyables实例的MonoBehaviour脚本中完成操作,通常你会在该脚本中声明可序列化的Buyables集合(列表/数组)用于Inspector面板赋值,示例声明如下:

// 该字段对应你在Inspector中填写的所有Buyables实例集合
public List<Buyables> allBuyables;

方法1:普通遍历实现(无需额外引入命名空间,兼容性好)

bool targetHasBought = false;
// 遍历集合匹配指定name的实例
foreach (Buyables item in allBuyables)
{
    if (item.name == "Apply some pressure")
    {
        targetHasBought = item.hasBought;
        break; // 匹配到后直接跳出循环,避免不必要的性能开销
    }
}

// 要赋值给其他bool变量直接写等号即可,示例:
bool yourCustomBool = targetHasBought;

方法2:LINQ简化实现(代码更简洁)

需要先在脚本顶部引入LINQ命名空间:

using System.Linq;

之后直接调用LINQ方法快速查询:

// 若未找到匹配实例则默认返回false
bool targetHasBought = allBuyables.FirstOrDefault(item => item.name == "Apply some pressure")?.hasBought ?? false;

// 赋值给其他变量的逻辑和上面一致
bool yourCustomBool = targetHasBought;

注意事项

  • 匹配的字符串需要和实例的name字段完全一致,包括大小写、空格、特殊符号
  • 上述两种方法默认取第一个匹配到的实例的hasBought值,若存在多个重名实例可以自行调整逻辑处理
  • 如果需要处理「未找到匹配实例」的特殊场景,可以自行添加判断分支输出日志或者走其他业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:48:05