75 lines
2.9 KiB
C#
75 lines
2.9 KiB
C#
using HarmonyLib;
|
||
using RimWorld;
|
||
using Verse;
|
||
|
||
namespace ArachnaeSwarm
|
||
{
|
||
// 1. 定义CompProperties来存储我们的数据
|
||
public class CompProperties_GiveHediffOnShot : CompProperties
|
||
{
|
||
public HediffDef hediffDef;
|
||
public float severityToAdd = 0.1f;
|
||
|
||
public CompProperties_GiveHediffOnShot()
|
||
{
|
||
compClass = typeof(CompGiveHediffOnShot);
|
||
}
|
||
}
|
||
|
||
// 2. 创建一个简单的Comp来挂载到武器上,它只负责持有数据
|
||
public class CompGiveHediffOnShot : ThingComp
|
||
{
|
||
public CompProperties_GiveHediffOnShot Props => (CompProperties_GiveHediffOnShot)props;
|
||
}
|
||
|
||
// 3. 创建Harmony补丁
|
||
// 补丁目标为 Verb_Shoot.TryCastShot。这是所有射击动作的通用入口。
|
||
[HarmonyPatch(typeof(Verb_Shoot), "TryCastShot")]
|
||
public static class Patch_Verb_Shoot_TryCastShot
|
||
{
|
||
// 使用[HarmonyPostfix]特性来创建一个在原方法执行后运行的补丁
|
||
// 添加一个bool类型的返回值`__result`,它代表了原方法的返回值
|
||
public static void Postfix(Verb_Shoot __instance, bool __result)
|
||
{
|
||
// __result 是原方法 TryCastShot 的返回值。
|
||
// 如果 __result 为 false,意味着射击动作因某些原因(如目标无效、没有弹药)失败了,我们就不应该添加Hediff。
|
||
if (!__result)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// __instance是原方法的实例对象,也就是那个Verb_Shoot
|
||
// 检查这个Verb是否来源于一个装备(武器)
|
||
if (__instance.EquipmentSource == null || __instance.CasterPawn == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// 尝试从武器上获取我们自定义的Comp
|
||
CompGiveHediffOnShot comp = __instance.EquipmentSource.GetComp<CompGiveHediffOnShot>();
|
||
if (comp == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// 检查XML中是否配置了hediffDef
|
||
if (comp.Props.hediffDef == null)
|
||
{
|
||
Log.ErrorOnce($"[ArachnaeSwarm] CompGiveHediffOnShot on {__instance.EquipmentSource.def.defName} has null hediffDef.", __instance.EquipmentSource.def.GetHashCode());
|
||
return;
|
||
}
|
||
|
||
// 为射击者(CasterPawn)添加或增加Hediff的严重性
|
||
Hediff hediff = __instance.CasterPawn.health.GetOrAddHediff(comp.Props.hediffDef);
|
||
hediff.Severity += comp.Props.severityToAdd;
|
||
|
||
// 检查Hediff是否带有HediffComp_Disappears组件
|
||
HediffComp_Disappears disappearsComp = hediff.TryGetComp<HediffComp_Disappears>();
|
||
if (disappearsComp != null)
|
||
{
|
||
// 如果有,则调用正确的方法重置它的消失计时器
|
||
disappearsComp.ResetElapsedTicks();
|
||
}
|
||
}
|
||
}
|
||
} |