I am writing a script for a Lightning Tower to target units in a tower defense game. I am currently working on the Lightning attack of the tower.
Here is the script that creates the Lightning:
Summary
local module = {}
function draw(p1, p2, Parent)
local dist = (p2.Position - p1.Position).Magnitude
local part = Instance.new("Part", Parent)
part.CanCollide = false
part.Anchored = true
part.Position = p1.Position
part.Material = "Neon"
part.BrickColor = BrickColor.new("New Yeller")
part.Size = Vector3.new(.5,.5,dist)
part.CFrame = CFrame.new(p1.Position, p2.Position) * CFrame.new(0,0,-dist/2)
end
module.CreateLightning = function(startPosition, endPosition, numberOfPoints)
local model = Instance.new("Model",game.Workspace)
local points = {}
for i = 0,numberOfPoints do
local offset = Vector3.new(math.random(-5,5),math.random(-2,2),math.random(-5,5))
if i == 0 or i == numberOfPoints then
offset = Vector3.new(0,0,0)
end
local part = Instance.new("Part", model)
part.Anchored = true
part.CanCollide = false
part.Size = Vector3.new(.5,.5,.5)
part.Material = "Neon"
part.BrickColor = BrickColor.new("New Yeller")
part.Position = startPosition + (endPosition - startPosition).Unit * i * (endPosition - startPosition).Magnitude/numberOfPoints
points[#points+1] = part
end
for i = 1,#points do
if points[i+1] ~= nil then
draw(points[i], points[i-1], model)
end
end
return model
end
return module
Here is the script that runs the Tower:
Summary
local tower = script.Parent.Position
local mobs = workspace.Board.MobRealm
local ball = tower.Parent.Ball
local ServerScriptService = game:GetService("ServerScriptService")
local lightningModule = require(ServerScriptService:WaitForChild("Lightning"))
local function FindNearestTarget()
local maxDistance = 70
local nearestTarget = nil
for i, target in ipairs(mobs:GetChildren()) do
local distance = (target.HumanoidRootPart.Position - tower.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
end
return nearestTarget
end
while true do
local target = FindNearestTarget()
if target then
game.TweenService:Create(ball,TweenInfo.new(2),
{
Transparency = 0,
Color = Color3.fromRGB(255, 170, 0)
}
):Play()
wait(2)
local model = lightningModule.CreateLightning(ball.Position, target.HumanoidRootPart.Position,10)
game.Debris:AddItem(model,1)
target.Humanoid:TakeDamage(25)
game.TweenService:Create(ball,TweenInfo.new(.5),
{
Transparency = .4,
Color = Color3.fromRGB(255, 0, 0)
}
):Play()
wait(.5)
end
task.wait(2.5)
--2.5 between shots
end
Whenever this is ran, I get the error:
ServerScriptService.Lightning:4: attempt to index nil with 'Position'
on Lightning Script
I have looked around for a solution but can’t seem to find a fix that works.
The lightning module was from a video, where no errors were present.