Jump to content

[NEED HELP] Coding: I want to make a character gradually lose health if it is at full sanity, and also to make the character spawning with half of its max sanity


Recommended Posts

I had been trying to find code lines that i could use as reference and trying to actually make the code myself but with no success for almost a week, if anyone could help me out i would be realy greatful.

Add this component to your player and let me know how it works. I made the threshold lower than 100% to fit visual ques, but you can tweak it to 1 again if you want.

Spoiler
STRINGS.NAMES.SHADOWBOUND_COMPONENT = "sanity" -- cause of death string

local function OnSanityDelta(inst, data)
	local self = inst.components.shadowbound
	self:CheckSanity(data.newpercent)
end

local function OnTimerDone(inst, data)
	local self = inst.components.shadowbound
    if data.name == "shadowbound" then
    	if not self.health then return end
		self.health:DoDelta(self.healthtick, nil, "shadowbound_component", false, nil, true)
		-- Rechecking sanity here would be redundant because OnSanityDelta is constant
    end
end

local ShadowBound = Class(function(self, inst)
	self.inst = inst
	self.inst:AddTag"shadowbound"
	self.threshold = 0.727 -- % sanity needed to activate decay (i picked this because thats when the brain shrivels but you can make it higher if you want
	self.healthtick = -1 -- health lost
	self.tick = 1 -- seconds to lose health
	if not inst.components.sanity then
		inst:AddComponent("sanity")
	end
	self.sanity = self.inst.components.sanity
	if not inst.components.timer then
		inst:AddComponent("timer")
	end
	self.timer = self.inst.components.timer
	if not inst.components.health then
		inst:AddComponent("health")
	end
	self.health = self.inst.components.health
	inst:ListenForEvent("timerdone", OnTimerDone)
	inst:ListenForEvent("sanitydelta", OnSanityDelta)
	inst:DoTaskInTime(0, function()
		self:CheckIfFirstTime()
		self:CheckSanity()
	end)
end)

function ShadowBound:CheckIfFirstTime()
	if not self.sanity or self.first then return end
	self.sanity:SetPercent(0.5, false)
	self.first = true
end

function ShadowBound:CheckSanity(percent)
	if not self.sanity then return end
	local percent = percent or self.sanity:GetPercent()
	if percent >= self.threshold then
		self:HealthDecayTask()
	end
end

function ShadowBound:HealthDecayTask()
	if not self.timer:TimerExists"shadowbound" then
		self.timer:StartTimer("shadowbound", self.tick)
	end
end

-- Basic saving/loading
function ShadowBound:Reset()
    self.first = nil
end

function ShadowBound:OnSave()
    return
	{
		first = self.first
	}
end

function ShadowBound:OnLoad(data)
	self.first = data.first or nil
end

return ShadowBound

 

If you want tips on what code to reference, I would recommend opening the command prompt and navigate to scripts and looking for things you want to add to components from there using grep or findstr. Scripts are bundled with your gamefiles. If you find a component command you want to use but are still stuck, it's useful to see commands used in action.

For this I had to look at the sanity, oldager, and health component for what I wanted.

Edited by oregu

I dont know if i am doing something wrong but now the game crashes wen i try to load the mod with the custom charcter now.

What's the error? Look at your Documents\Klei\DoNotStarveTogether in client_log.txt or master_server_log.txt and do ctrl + F "LUA ERROR" if the game closes

Edited by oregu

Here is what it says in the client_log:

 

LUA ERROR stack traceback:
        =[C] in function 'assert'
        scripts/mainfunctions.lua(160,1)
        =(tail call) ?
        =[C] in function 'xpcall'
        scripts/mods.lua(188,1)
        scripts/mods.lua(665,1) in function 'RegisterPrefabs'
        scripts/gamelogic.lua(316,1) in function 'LoadAssets'
        scripts/gamelogic.lua(1088,1) in function 'cb'
        scripts/shardindex.lua(214,1) in function 'OnLoadSaveDataFile'
        scripts/shardindex.lua(231,1)
        =[C] in function 'GetPersistentStringInClusterSlot'
    ...
        =[C] in function 'GetPersistentString'
        scripts/saveindex.lua(285,1) in function 'Load'
        scripts/gamelogic.lua(1324,1) in function 'callback'
        scripts/playerprofile.lua(1747,1) in function 'Set'
        scripts/playerprofile.lua(1587,1)
        =[C] in function 'GetPersistentString'
        scripts/playerprofile.lua(1585,1) in function 'Load'
        scripts/gamelogic.lua(1323,1) in main chunk
        =[C] in function 'require'
        scripts/mainfunctions.lua(1387,1)    
[00:02:09]: Disabling emily (Emily) because it had an error.    
[00:02:09]: [string "scripts/mainfunctions.lua"]:160: Error loading file prefabs/emily
[string "../mods/emily/scripts/prefabs/emily.lua"]:86: '<eof>' expected near 'STRINGS'
LUA ERROR stack traceback:
        =[C] in function 'assert'
        scripts/mainfunctions.lua(160,1)
        =(tail call) ?
        =[C] in function 'xpcall'
        scripts/mods.lua(188,1)
        scripts/mods.lua(665,1) in function 'RegisterPrefabs'
        scripts/gamelogic.lua(316,1) in function 'LoadAssets'
        scripts/gamelogic.lua(1088,1) in function 'cb'
        scripts/shardindex.lua(214,1) in function 'OnLoadSaveDataFile'
        scripts/shardindex.lua(231,1)
        =[C] in function 'GetPersistentStringInClusterSlot'
    ...
        =[C] in function 'GetPersistentString'
        scripts/saveindex.lua(285,1) in function 'Load'
        scripts/gamelogic.lua(1324,1) in function 'callback'
        scripts/playerprofile.lua(1747,1) in function 'Set'
        scripts/playerprofile.lua(1587,1)
        =[C] in function 'GetPersistentString'
        scripts/playerprofile.lua(1585,1) in function 'Load'
        scripts/gamelogic.lua(1323,1) in main chunk
        =[C] in function 'require'
        scripts/mainfunctions.lua(1387,1)
[00:02:09]: [string "scripts/mainfunctions.lua"]:160: Error loading file prefabs/emily
[string "../mods/emily/scripts/prefabs/emily.lua"]:86: '<eof>' expected near 'STRINGS'
LUA ERROR stack traceback:
        =[C] in function 'assert'
        scripts/mainfunctions.lua(160,1)
        =(tail call) ?
        =[C] in function 'xpcall'
        scripts/mods.lua(188,1)
        scripts/mods.lua(665,1) in function 'RegisterPrefabs'
        scripts/gamelogic.lua(316,1) in function 'LoadAssets'
        scripts/gamelogic.lua(1088,1) in function 'cb'
        scripts/shardindex.lua(214,1) in function 'OnLoadSaveDataFile'
        scripts/shardindex.lua(231,1)
        =[C] in function 'GetPersistentStringInClusterSlot'
    ...
        =[C] in function 'GetPersistentString'
        scripts/saveindex.lua(285,1) in function 'Load'
        scripts/gamelogic.lua(1324,1) in function 'callback'
        scripts/playerprofile.lua(1747,1) in function 'Set'
        scripts/playerprofile.lua(1587,1)
        =[C] in function 'GetPersistentString'
        scripts/playerprofile.lua(1585,1) in function 'Load'
        scripts/gamelogic.lua(1323,1) in main chunk
        =[C] in function 'require'
        scripts/mainfunctions.lua(1387,1)    
[00:02:09]: Mod: emily (Emily)      Registering prefab file: prefabs/emily_none    
[00:02:09]: Mod: emily (Emily)        emily_none    
[00:02:09]: Mod: emily (Emily)      Registering default mod prefab    
[00:02:10]:     LOAD BE    
[00:02:29]:     LOAD BE: done    
[00:02:29]: Begin Session: 7A9707220D1A5A67
[00:02:29]: saving to server_temp/server_save    
[00:02:29]: OVERRIDE: setting    healthpenalty    to    always    
[00:02:29]: OVERRIDE: setting    lessdamagetaken    to    none    
[00:02:29]: MiniMapComponent::AddAtlas( minimap/minimap_data1.xml )
[00:02:29]: MiniMapComponent::AddAtlas( minimap/minimap_data2.xml )
[00:02:29]: MiniMapComponent::AddAtlas( ../mods/emily/images/map_icons/emily.xml )
[00:02:29]: Loading 20 new character(s)    
[00:02:31]: Could not preload undefined prefab (emily)
[00:02:31]: Total 20 character(s) loaded    
[00:02:31]: Loading Nav Grid    
[00:02:31]: World generated on build 654051 with save version: 5.151, using seed: 1710706402    
[00:02:31]: OVERRIDE: setting    ghostenabled    to    always    
[00:02:31]: OVERRIDE: setting    basicresource_regrowth    to    none    
[00:02:31]: OVERRIDE: setting    portalresurection    to    none    
[00:02:31]: OVERRIDE: setting    spawnmode    to    fixed    
[00:02:31]: OVERRIDE: setting    ghostsanitydrain    to    always    
[00:02:40]: Reconstructing topology    
[00:02:40]:     ...Sorting points    
[00:02:40]:     ...Sorting edges    
[00:02:40]:     ...Connecting nodes    
[00:02:40]:     ...Validating connections    
[00:02:40]:     ...Housekeeping    
[00:02:40]:     ...Done!    
[00:02:40]: 1 uploads added to server. From server_temp
[00:02:40]: Telling Client our new session identifier: 7A9707220D1A5A67
[00:02:40]: Check for write access: TRUE
[00:02:40]: Check for read access: TRUE
[00:02:40]: Available disk space for save files: 23975 MB
[00:02:40]: ModIndex: Load sequence finished successfully.    
[00:02:40]: Reset() returning
[00:02:56]: Server registered via geo DNS in eu-central-1
 

 

and also here is a screenshot in game if it helps

Screenshot 2025-02-16 112051.png

<eof> is do or then
The way you add components to put 
inst:AddComponent("componentname") in your player function (im guessing master_postinit for this one)
your component file must also be located in a file in scripts/components/componentname.lua in your mod folder so it can be found automatically. (so what i sent is its own file) if you are having trouble with STRINGS still or want to move them somewhere else you might need to do GLOBAL.STRINGS.

Edited by oregu

okay i have resolved that but now the game chrashes wen i try to play as the character.Here is the lua error that it gave me:

 

LUA ERROR stack traceback:
../mods/emily/scripts/components/componentname.lua:5 in (local) fn (Lua) <3-6>
   inst = 121922 -  (valid:true)
   data = table: 000000009A1AE230
   self = nil
scripts/entityscript.lua:1215 in (method) PushEvent (Lua) <1202-1229>
   self (valid:true) =
      DynamicShadow = DynamicShadow (0000000017DEC4D0)
      inlimbo = false
      GetMoistureRateScale = function - scripts/prefabs/player_common.lua:254
      _lunarportalmax = table: 000000005D0F2590
      CanSeePointOnMiniMap = function - scripts/prefabs/player_common_extensions.lua:887
      skeleton_prefab = skeleton_player
      EnableBoatCamera = function - scripts/prefabs/player_common.lua:904
      playercolour = table: 000000005EC28930
      jointask = PERIODIC 121922: 0.000000
      AnimState = AnimState (0000000017DEB300)
      Light = Light (0000000017DEC620)
      OnRemoveEntity = function - scripts/prefabs/player_common.lua:1099
      pendingtasks = table: 000000005D0E9B70
      ApplySkinOverrides = function - scripts/prefabs/player_common.lua:1646
      ResetMinimapOffset = function - scripts/prefabs/player_common.lua:1473
      sg = sg="wilson", state="idle", time=0.00, tags = "idle,canrotate,"
      IsHUDVisible = function - scripts/prefabs/player_common.lua:1451
      ApplyScale = function - scripts/prefabs/player_common.lua:1584
      SetGhostMode = function - scripts/prefabs/player_common.lua:913
      ShowActions = function - scripts/prefabs/player_common.lua:1455
      SetGymStartState = function - scripts/prefabs/player_common.lua:55
      IsChannelCastingItem = function - scripts/prefabs/player_common.lua:290
      actionreplica = table: 00000000153B1570
      event_listening = table: 000000005D0E9EE0
      actioncomponents = table: 00000000153B0E40
      lower_components_shadow = table: 00000000153B1750
      GetMaxMoisture = function - scripts/prefabs/player_common.lua:244
      OnPostActivateHandshake_Server = function - scripts/prefabs/player_common_extensions.lua:1007
      cameradistancebonuses = table: 000000005D0F42F0
      CanUseTouchStone = function - scripts/prefabs/player_common.lua:194
      updatecomponents = table: 000000005D0EC0A0
      xpgeneration_task = PERIODIC 121922: 480.000000
      ShakeCamera = function - scripts/prefabs/player_common.lua:1525
      OnPostActivateHandshake_Client = function - scripts/prefabs/player_common_extensions.lua:988
      persists = false
      MiniMapEntity = MiniMapEntity (0000000017DEC530)
      IsFreezing = function - scripts/prefabs/player_common.lua:214
      replica = table: 00000000153B17A0
      GetTemperature = function - scripts/prefabs/player_common.lua:204
      GUID = 121922
      soundsname = willow
      ApplyAnimScale = function - scripts/prefabs/player_common.lua:1614
      starting_inventory = table: 000000005BD635A0
      ghostenabled = true
      _underleafcanopy = net_bool (000000005D0F2BD0)
      IsChannelCasting = function - scripts/prefabs/player_common.lua:286
      EnableMovementPrediction = function - scripts/prefabs/player_common.lua:843
      worldstatewatching = table: 000000005D0EB830
      SwapAllCharacteristics = function - scripts/prefabs/player_common.lua:2111
      SetCameraZoomed = function - scripts/prefabs/player_common.lua:1511
      SetGymStopState = function - scripts/prefabs/player_common.lua:64
      TargetForceAttackOnly = function - scripts/prefabs/player_common.lua:51
      CanSeeTileOnMiniMap = function - scripts/prefabs/player_common_extensions.lua:883
      IsNearDanger = function - scripts/prefabs/player_common.lua:17
      YOTB_isskinunlocked = function - scripts/prefabs/player_common.lua:92
      YOTB_issetunlocked = function - scripts/prefabs/player_common.lua:85
      Transform = Transform (0000000017DEBC30)
      IsInMiasma = function - scripts/prefabs/player_common.lua:271
      AddCameraExtraDistance = function - scripts/prefabs/player_common.lua:1495
      ScreenFlash = function - scripts/prefabs/
[00:05:17]: [string "../mods/emily/scripts/components/componentn..."]:5: attempt to index local 'self' (a nil value)
LUA ERROR stack traceback:
    ../mods/emily/scripts/components/componentname.lua:5 in (local) fn (Lua) <3-6>
    scripts/entityscript.lua:1215 in (method) PushEvent (Lua) <1202-1229>
    scripts/components/sanity.lua:307 in (method) DoDelta (Lua) <279-336>
    scripts/components/sanity.lua:245 in (method) SetMax (Lua) <242-246>
    ../mods/emily/scripts/prefabs/emily.lua:71 in (upvalue) master_postinit (Lua) <57-82>
    scripts/prefabs/player_common.lua:2681 in (field) fn (Lua) <2170-2724>
    scripts/mainfunctions.lua:336 in () ? (Lua) <325-371>
    =[C]:-1 in (method) SendSpawnRequestToServer (C) <-1--1>
    scripts/mainfunctions.lua:1991 in (local) cb (Lua) <1966-1992>
    scripts/frontend.lua:666 in (method) DoFadingUpdate (Lua) <630-670>
    scripts/frontend.lua:734 in (method) Update (Lua) <688-890>
    scripts/update.lua:95 in () ? (Lua) <33-138>

Screenshot 2025-02-16 140514.png

Edited by DeadlyFox

it's scripts/components/shadowbound.lua and AddComponent("shadowbound") for the component i sent you. 

if you want to rename a component it's best to replace every instance of the component name with your .lua file name and change AddComponent(name) to your component name.
the reason it throws an error is because i made the component name out of scope. line 5 would have to be local self = inst.components.componentname (i dont think you want a component named componentname though)

Edited by oregu
Quote

 

It works perfectly! Thanks a lot that you took your patience to help me out, you are the best, i am eternally in debt to you.

Edited by DeadlyFox
  • Like 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
  • Create New...