How do I prevent these repetitions from happening?

Hi! I’m trying to make a fighting game with skill movesets and I’m running into a problem where whenever I press an input, all the 4 skills are called in at once (shown by the output when I print them)

image_2024-01-14_181709589

Does anyone know why this is happening? I want it to whenever I press 1,2,3, or 4 it will call to the corresponding skill and not all of them at once.

This is the code:

local skillButtons = {
	Enum.KeyCode.One,
	Enum.KeyCode.Two,
	Enum.KeyCode.Three,
	Enum.KeyCode.Four,
}

local currentSkillIndex = 0

local function activateSkill(skillIndex)
	for i, skillButton in ipairs(skillButtons) do
		local isActivated = (i == skillIndex)
		print("Skill" .. i) --// Prints which skill I have just equipped
	end
end

UserInputService.InputBegan:Connect(function(key)
	for i, skillButton in ipairs(skillButtons) do
		if key.KeyCode == skillButton then
			if currentSkillIndex ~= i then
				currentSkillIndex = i
				activateSkill(currentSkillIndex)
			elseif currentSkillIndex == i then
				currentSkillIndex = 0
				activateSkill(currentSkillIndex)
			end
			break
		end
	end
end)
2 Likes

Hi there. So I can see that you have a for loop going through all the skillButtons which will of course display all the skills available as seen in activateSkill(). You might be better off just throwing away the for loop in activateSkill all together and just use the skillIndex along with skillButtons.

Example:

Instead of

local function activateSkill(skillIndex)
	for i, skillButton in ipairs(skillButtons) do
		local isActivated = (i == skillIndex)
		print("Skill" .. i) --// Prints which skill I have just equipped
	end
end

do something like

local function activateSkill(skillIndex)
	local isActivated = skillIndex -- idk why you need this boolean
	print("Skill" .. skillIndex) --// Prints which skill I have just equipped
end
2 Likes

Just use an if statement that runs the skill code when the isActivated variable is true. i.e.

local function activateSkill(skillIndex)
	for i, skillButton in ipairs(skillButtons) do
		local isActivated = (i == skillIndex)
                if isActived then
		      print("Skill" .. i) --// Prints which skill I have just equipped
               end
	end
end
1 Like