To modify your Roblox shield system to allow an NPC to have a shield that can be broken but doesn't run out of time, you'll need to adjust your code so that it can handle both players and NPCs, and allow for shields with indefinite durations.
Here's how you can achieve this:
1. Modify the ShieldModule to Accept Both Players and NPCs
Currently, your ShieldModule functions accept player as a parameter. For NPCs, there is no player object, so we'll need to adjust the functions to accept a character instead. Additionally, we'll introduce a duration parameter that specifies how long the shield should last. If the duration is not specified or is zero, the shield won't expire over time.
Changes:
- Modify the
ShieldModule.Shield function to accept character and duration.
- Use
character as the key in your shieldData table instead of player.
- Adjust the
DestroyShield and Disable functions similarly.
Updated ShieldModule Code:
-- ModuleScript inside ReplicatedStorage.GameModules.Shield
local ShieldModule = {}
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local shieldData = {}
-- Reference to the ShieldParticles attachment (ensure the path is correct)
local shieldAttachmentTemplate = script.ParticleHold:WaitForChild("ShieldParticles")
-- Exposed from the server script
ShieldModule.ShieldBreakEvent = nil
ShieldModule.restorePlayerStats = nil
-- Function to cancel any running timers for the character
local function cancelTimers(character)
local data = shieldData[character]
if data then
if data.shieldTimer then
data.shieldTimer:Disconnect()
data.shieldTimer = nil
end
if data.cooldownTimer then
data.cooldownTimer:Disconnect()
data.cooldownTimer = nil
end
end
end
function ShieldModule.Shield(character, duration) -- duration in seconds, nil or 0 for infinite duration
if not character or not character:FindFirstChild("Torso") then return end
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if not humanoid then return end
-- Check if ShieldReady is false
local shieldReady = character:FindFirstChild("ShieldReady")
if shieldReady and not shieldReady.Value then
return
end
-- If ShieldActive is already true, shield is already active
local shieldActive = character:FindFirstChild("ShieldActive")
if shieldActive and shieldActive.Value then
return
end
-- Set ShieldActive to true
shieldActive = shieldActive or Instance.new("BoolValue", character)
shieldActive.Name = "ShieldActive"
shieldActive.Value = true
-- Ensure ShieldReady is true
shieldReady = shieldReady or Instance.new("BoolValue", character)
shieldReady.Name = "ShieldReady"
shieldReady.Value = true
-- Clone the ShieldParticles attachment and parent it to the character's Torso
local shieldAttachment = shieldAttachmentTemplate:Clone()
shieldAttachment.Parent = character:FindFirstChild("Torso")
shieldAttachment.Name = "ShieldAttachment"
-- Store shield data
shieldData[character] = shieldData[character] or {}
shieldData[character].attachment = shieldAttachment
-- Start shield timer if duration is specified
if duration and duration > 0 then
local shieldStartTime = tick()
shieldData[character].shieldStartTime = shieldStartTime
-- Use Heartbeat to update color every frame and check duration
local function onHeartbeat(deltaTime)
local currentTime = tick()
local elapsedTime = currentTime - shieldStartTime
local data = shieldData[character]
if not data then return end
-- Update particle color to become more red over time
local progress = math.clamp(elapsedTime / duration, 0, 1)
local redColor = Color3.new(1, 0, 0) -- Red
local startColor = Color3.new(0, 1, 0) -- Green
local currentColor = startColor:Lerp(redColor, progress)
-- Update color of particles and PointLight
for _, descendant in pairs(shieldAttachment:GetDescendants()) do
if descendant:IsA("ParticleEmitter") then
local colorSequence = ColorSequence.new(currentColor)
descendant.Color = colorSequence
elseif descendant:IsA("PointLight") then
descendant.Color = currentColor
end
end
-- Check if duration seconds have elapsed
if elapsedTime >= duration then
-- Shield duration is over
ShieldModule.DestroyShield(character, true) -- true indicates overTime
end
end
shieldData[character].shieldTimer = RunService.Heartbeat:Connect(onHeartbeat)
end
end
function ShieldModule.DestroyShield(character, overTime)
local data = shieldData[character]
if not data then return end
cancelTimers(character)
-- Rest of the code
-- Similar to before, adjusting to use 'character'
-- Turn off ShieldActive and ShieldReady
local shieldActive = character:FindFirstChild("ShieldActive")
local shieldReady = character:FindFirstChild("ShieldReady")
if shieldActive then
shieldActive.Value = false
end
if shieldReady then
shieldReady.Value = false
else
shieldReady = Instance.new("BoolValue", character)
shieldReady.Name = "ShieldReady"
shieldReady.Value = false
end
-- Start cooldown timer (6 seconds if destroyed over time, else 3 seconds)
local cooldownStartTime = tick()
local cooldownDuration = overTime and 6 or 3
local function onCooldownHeartbeat()
local currentTime = tick()
local elapsedTime = currentTime - cooldownStartTime
if shieldReady.Value == true then
shieldReady.Value = false -- Prevent exploiters from forcing it back on
end
if elapsedTime >= cooldownDuration then
shieldReady.Value = true
-- Destroy cooldown timer
if data.cooldownTimer then
data.cooldownTimer:Disconnect()
data.cooldownTimer = nil
end
end
end
data.cooldownTimer = RunService.Heartbeat:Connect(onCooldownHeartbeat)
-- Play sounds if character is player OR NPC
require(ReplicatedStorage:FindFirstChild("GameModules"):FindFirstChild("PlaySound")).play(
ReplicatedStorage.GameSounds.ShieldSounds.Stop,
character:FindFirstChild("HumanoidRootPart")
)
if overTime then
require(ReplicatedStorage:FindFirstChild("GameModules"):FindFirstChild("PlaySound")).play(
ReplicatedStorage.GameSounds.ShieldSounds.Break,
character:FindFirstChild("HumanoidRootPart")
)
-- If character corresponds to a player, fire ShieldBreakEvent to client to play break animation
local player = Players:GetPlayerFromCharacter(character)
if player and ShieldModule.ShieldBreakEvent then
ShieldModule.ShieldBreakEvent:FireClient(player)
end
end
-- Restore player's walk speed and jump power if applicable
if ShieldModule.restorePlayerStats then
local player = Players:GetPlayerFromCharacter(character)
if player then
ShieldModule.restorePlayerStats(player)
end
end
-- Tween light brightness over 1.5 seconds, then destroy attachment
if data.attachment and data.attachment.Parent then
local shieldAttachment = data.attachment
-- Turn off particles
for _, descendant in pairs(shieldAttachment:GetDescendants()) do
if descendant:IsA("ParticleEmitter") then
descendant.Enabled = false
end
end
local pointLight = shieldAttachment:FindFirstChildWhichIsA("PointLight")
if pointLight then
local initialBrightness = pointLight.Brightness
local targetBrightness = 0
local tweenInfo = TweenInfo.new(1.5)
local tween = TweenService:Create(pointLight, tweenInfo, {Brightness = targetBrightness})
tween:Play()
end
task.delay(1.5, function()
shieldAttachment:Destroy()
end)
data.attachment = nil
end
-- Clean up shieldData
shieldData[character] = nil
end
function ShieldModule.Disable(character)
ShieldModule.DestroyShield(character, false)
end
return ShieldModule
2. Adjust the Server Script to Handle the Modified Module
In your server script, you'll need to adjust how you call the ShieldModule functions to accommodate the changes. Specifically, when you activate a shield for a player or NPC, you need to pass the character and the desired duration.
For Player Shields (3-Second Duration):
-- Inside your ShieldEvent.OnServerEvent handler
ShieldModule.Shield(player.Character, 3) -- Shield lasts for 3 seconds
For NPC Shields (Indefinite Duration):
-- When you want to activate a shield for an NPC
ShieldModule.Shield(npcCharacter, 0) -- Shield lasts indefinitely until broken
3. Handle Player Statistics Appropriately
In your server script, you have playerStats to store players' walk speed and jump power. Since NPCs don't require this, you can adjust your restorePlayerStats function to handle only players.
Updated restorePlayerStats Function:
-- Function to restore player's walk speed and jump power
function restorePlayerStats(player)
local character = player.Character
if character then
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid and playerStats[player] then
humanoid.WalkSpeed = playerStats[player].WalkSpeed
humanoid.JumpPower = playerStats[player].JumpPower
playerStats[player] = nil
end
end
end
-- Expose restorePlayerStats to the ShieldModule
ShieldModule.restorePlayerStats = restorePlayerStats
4. Adjust Client-Side Code if Necessary
Since NPCs don't have a client to receive events, any client-side code that handles shield breaking animations or effects for NPCs can be omitted or handled differently. Ensure that when you fire the ShieldBreakEvent, you check whether the character is a player.
Example Adjustment:
-- Inside ShieldModule.DestroyShield function
local player = Players:GetPlayerFromCharacter(character)
if player and ShieldModule.ShieldBreakEvent then
ShieldModule.ShieldBreakEvent:FireClient(player)
end
5. Implement Breaking the NPC's Shield
When you want to break the NPC's shield (e.g., when the NPC is attacked), you can call the ShieldModule.DestroyShield function directly with the NPC's character.
Example:
-- When the NPC's shield should be broken
ShieldModule.DestroyShield(npcCharacter, false) -- 'false' indicates it's not destroyed over time
Summary
By making these adjustments, you can effectively modify your shield system to allow NPCs to have shields that can be broken but don't run out of time. The key changes involve:
- Modifying the
ShieldModule to accept a character and duration parameter.
- Adjusting your data structures (
shieldData, playerStats) to index by character instead of player.
- Passing the appropriate
duration when activating shields for players (3 seconds) and NPCs (indefinite).
- Handling client-side events and player-specific functionalities only for players.
With these modifications, your shield system should function correctly for both players and NPCs, providing the desired behavior.