Hello there! I was developing a Tower Defense game and this error message appears, I used GnomeCode’s module script but I modified it a bit.
Here’s the script.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Events = ReplicatedStorage:WaitForChild("Events")
local PlaceTowerEvent = Events:WaitForChild("TowerPlaced")
local AnimateTowerEvent = Events:WaitForChild("AnimateTower")
local Tower = {}
function FindNearestTarget(NewTower, Range)
local NearestTarget = nil
for i, Target in ipairs(workspace.Enemies:GetChildren()) do
local Distance = (Target.HumanoidRootPart.Position - NewTower.HumanoidRootPart.Position).Magnitude
if Range < Distance then
NearestTarget = Target
Range = Distance
end
end
return NearestTarget
end
function Tower.Attack(NewTower, Player)
local Config = NewTower.Statistics
local Target = FindNearestTarget(NewTower,Config.CurrentRange.Value)
if Target and Target:FindFirstChild("Humanoid") and Target.Humanoid.Health > 0 then
local TargetCFrame = CFrame.lookAt(NewTower.HumanoidRootPart.Position, Target.HumanoidRootPart.Position)
NewTower.HumanoidRootPart.BodyGyro.CFrame = TargetCFrame
AnimateTowerEvent:FireClient(NewTower, "Attack")
Target.Humanoid:TakeDamage(Config.CurrentDamage)
local CurrentHP = Target.Humanoid
Target.Humanoid.Changed:Connect(function(NewHealth)
CurrentHP = NewHealth
Player.Cash.Value += 1
return
end)
task.wait(Config.CurrentFirerate.Value)
end
task.wait(0.1)
Tower.Attack(NewTower, Player)
end
function Tower.Spawn(Player, Name, Cframe)
local ExistingTower = ReplicatedStorage.Towers:FindFirstChild(Name)
if ExistingTower then
local NewTower = ExistingTower:Clone()
NewTower.HumanoidRootPart.CFrame = Cframe
NewTower.Parent = workspace.Towers
NewTower.HumanoidRootPart:SetNetworkOwner(nil)
local BodyGyro = Instance.new("BodyGyro")
BodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge)
BodyGyro.D = 0
BodyGyro.CFrame = NewTower.HumanoidRootPart.CFrame
BodyGyro.Parent = NewTower.HumanoidRootPart
-- PhysicsEngine Collision V1
for i, Object in ipairs(NewTower:GetDescendants()) do
if Object:IsA("BasePart") then
PhysicsEngine:SetPartCollisionGroup(Object, "Tower")
end
end
coroutine.wrap(Tower.Attack)(NewTower, Player)
else
warn("Confirmed Tower doesn't exist:", Name)
end
end
PlaceTowerEvent.OnServerEvent:Connect(Tower.Spawn)
return Tower