Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Accessing a enemy humanoid?

So I'm making a turn-based RPG and I want the combat to start when the player touches the enemy. And the way the player is attacking the enemy is it finds the enemy humanoid in the workspace and makes it take damage. But, the enemy name is not the word "enemy" all the time, meaning I can't just access the name of the enemy easily all the time.

So because of this, I decided to make a script that changes the value of a string in a Gui. And the name of this string is the enemy's name. (The Below code is the .Touched script that sets the value)

local CombatGui = script.Parent
local CurrentEnemyName = CombatGui.CurrentEnemyName
local debounce = false
local hrp = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")

hrp.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Enemy") and debounce == false then
		print("Touched!")
		debounce = true
		script.Parent.Enabled = true
		script.Parent.Parent.PlayerHealth.Enabled = true
		CurrentEnemyName.Value = hit.Parent.Name
		end
end)

local enemy = game.Workspace:FindFirstChild(CurrentEnemyName.Value)
local eHumanoid = enemy:WaitForChild("Enemy")

From the last 2 variables, I'm trying to find a model in the Workspace that has the same name as the enemy im touching, but I don't know how to do this. So if you kind people of Scripting Helpers could help me fix this, I would be eternally grateful! (I'm sorry if this was kind of long or confusing btw.)

1 answer

✓ Accepted answer

you can create a in pairs loop to find the children of the workspace, and see if they have the same name as the enemy you touched.

you can also wrap the loop with spawn(function() you can find more information about it here: link

local CombatGui = script.Parent
local CurrentEnemyName = CombatGui.CurrentEnemyName
local debounce = false
local hrp = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")

hrp.Touched:Connect(function(hit)
    if hit.Parent:FindFirstChild("Enemy") and debounce == false then
        print("Touched!")
        debounce = true
        script.Parent.Enabled = true
        script.Parent.Parent.PlayerHealth.Enabled = true
        CurrentEnemyName.Value = hit.Parent.Name
		for i,v in pairs (game.Workspace:GetChildren()) do
			if v.Name == CurrentEnemyName.Value then
					-- do stuff
			end
		end
        end
end)

local enemy = game.Workspace:FindFirstChild(CurrentEnemyName.Value)
local eHumanoid = enemy:WaitForChild("Enemy")

This discussion is preserved as it was. New answers, comments, and votes are closed.