How to check if a player is STILL touching a part

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

  2. What is the issue? Include screenshots / videos if possible!

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

-- This is an example Lua code block

I want to make a wall red while a player is touching a part and another wall green if the first wall is red for two seconds. I’m only a beginner in scripting and can’t seem to find out the issue in my code. Therefore, I’m seeking help from you guys.
Here’s a video of what’s happening:
robloxapp-20220530-1659441.wmv (794.5 KB)
The first wall seems to flicker between red and black while the second one remains black.
Here’s my code:

wait(5)
print("Script is has started")

local wall = game.Workspace.Wall
local wall2 = game.Workspace.WallTheSecond
local grass = game.Workspace.GrassPatch
local wallIsRed = false
wall.Color = Color3.fromRGB(0, 0, 0)
wall2.Color = Color3.fromRGB(0, 0, 0)

grass.Touched:Connect(function()
	wallIsRed = true
	wall.Color = Color3.fromRGB(255, 0, 0)
end)

grass.TouchEnded:Connect(function()
	wallIsRed = false
	wall.Color = Color3.fromRGB(0, 0, 0)
end)

if wallIsRed then
	wait(2)
	wall2.Color = Color3.fromRGB(0, 255, 0)
end

Again, I’m only a beginner in coding so please correct me if I’m missing something.

3 Likes

oh damn i forgot to delete the first thing

1 Like

This is untested, but it’s the general idea.

function StillTouchingObject(Object: Instance) : Boolean
for Index, BasePart in next, Object:GetTouchingParts() do
if (not BasePart:IsA('MeshPart') or not BasePart.Parent:IsA('Model')) then continue end;

if BasePart:IsDescendantOf(Character) then return true; end;
end;
return false;
end;

local IsTouching = StillTouchingObject(YOUROBJECT);
print(IsTouching);

or to stop an action when the player stops touching an object:

RunService.RenderStepped:Connect(function()
local IsTouching = StillTouchingObject(YOUROBJECT?);
if not IsTouching then return end;
print('Player Touching Object');
end);
2 Likes

What do I replace “Character” with?

No Character is the players Character, is this a local script or server script btw?

It’s a local script placed in StarterCharacterScripts as I’m gonna use this

Perhaps look at using a resource such as ZonePlus

*StarterPlayerScripts (If I’m tryna edit the post it’sgiving the 403 error)

Add this to the top of your script, then everything else I said, to the bottom.

local PlayerService = game:GetService('Players');
local Player = PlayerService.LocalPlayer;
local Character = (Player.Character or Player.CharacterAdded:Wait());