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

如何通过读取TXT字符串设置Rigidbody2D.bodyType

解决方案

要把字符串形式的刚体类型转回RigidbodyType2D枚举,直接用C#的枚举转换方法即可,推荐用安全容错的Enum.TryParse,避免字符串不匹配时抛出异常:

基础转换(适用于字符串绝对合法的场景)

// 从TXT读取的刚体类型字符串
string bodyTypeStr = assetBodyType[j];
// 将字符串转换为RigidbodyType2D枚举
RigidbodyType2D targetType = (RigidbodyType2D)Enum.Parse(typeof(RigidbodyType2D), bodyTypeStr);
// 赋值给目标GameObject的Rigidbody2D
assetsToSave[j].GetComponent<Rigidbody2D>().bodyType = targetType;

安全转换(推荐,处理非法字符串)

如果担心读取的字符串可能存在拼写错误或不匹配的情况,用Enum.TryParse做容错处理,避免程序崩溃:

string bodyTypeStr = assetBodyType[j];
RigidbodyType2D targetType;
if (Enum.TryParse(bodyTypeStr, out targetType))
{
    assetsToSave[j].GetComponent<Rigidbody2D>().bodyType = targetType;
}
else
{
    // 字符串不合法时的兜底逻辑,比如设为默认的Dynamic类型
    assetsToSave[j].GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
}

额外说明

你之前用bodyType.ToString()存储的字符串,和RigidbodyType2D枚举的名称完全一致(比如"Kinematic"对应RigidbodyType2D.Kinematic),所以直接转换就能正常工作,不需要额外做映射处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:32:10