Any tips on how to improve this code?

Has anyone got any tips for this code that I wrote?

local Players = game:GetService("Players")
local runService = game:GetService("RunService")

local AI = require(game:GetService("ServerScriptService"):WaitForChild("Modules").AIClass)

local doorOpen = false
local lookTick = 0
local lookAway = 0

local during = false
local player

local Guy = AI.new(workspace["The creatures"].Guy,0,0,100)
Guy.CanTeleport = true

wait(5)

local function Teleport()
	if doorOpen then return end
	local playerList = Players:GetChildren()
	if #playerList ~= 0 then
		local randomPlayer = playerList[math.random(1,#playerList)]
		print(randomPlayer)
		local char = randomPlayer.Character
		Guy:Teleport(randomPlayer)
		return randomPlayer
	end
end

local function MonsterAttack(player)
	local char = player.Character
	if lookAway >= 10 then
		Guy.Model.HumanoidRootPart.Position += Vector3.new(0,0,10)
		lookTick = 0
		lookAway = 0
		wait(1)
		print("ok")
		during = false
		return false
	end
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {char:GetChildren()}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local result = workspace:Raycast(char.Torso.Position, char.Torso.CFrame.LookVector*6, raycastParams)
	if result and result.Instance.Parent.Name == "Guy" then
		lookTick += 1
		print(lookTick)
		if lookTick >= 5 then
			Guy:Attack(player)
			player:Kick("killed trol")
			during = false
			result = nil
			lookAway = 0
			lookTick = 0
			return true
			
		end
	else
		lookAway += 1
		lookTick = 0
	end
end

local function handler()
	if not player then
		wait(2)
		player = Teleport()
	end
	if player then
		local attacked = MonsterAttack(player)
		if attacked ~= nil then
			print("test")
			player = nil
			attacked = nil
		end
	end
end

while true do
	handler()
	wait(1)
end

this code gets a random player, and then the monster teleports to them and if the player looks at the monster for 5 seconds, they die and get kicked but if the player looks away for 15 seconds, the monster finds another player to teleport to. This code works fine, however I think I have implemented multiple things that is bad practice and I want some feedback on this if there is anything I have done that is bad practice and where I can improve upon.

More context please, not a single sentence and a code dump. What does this code do? What tips are you looking for specifically and which parts of the code specifically don’t fit well? What have you tried already that hasn’t worked out? Feel free to check out the Code Review category guidelines for some pointers on what kind of information would be good to include to help guide us in knowing what feedback you’d like.

3 Likes