Issue with detecting parts and if statements

I am currently working on a small project called “burger”.

SUMMARY:

In this game, you essentially start in a Main Menu screen and click play. Your camera switches to a horizontal view. There is a 3 second countdown on screen. Then, a plate in the Workspace tweens in from the right. An order menu GUI for a burger also tweens in from the top right. The player then attempts to replicate the order of the burger as fast as they can with as much accuracy as then can. Based on their input, they get a score and earn points. The plate and the burger they created then tween to the left of their screen.


GOAL:

Currently, I have a variable checking if the player is doneMakingBurger. I have set it to false by default. There is then an if statement being looped by a while true do loop checking if the burger is done being made. If it is done being made(true), the script should continue and first check if a plate already exists. If the plate already exists in the Workspace, it will tween the plate off the left side of the player’s screen, move onto else, where a plate is cloned from ReplicatedStorage and tweened in from the right side of the player’s screen.


ISSUE:

For some reason, when I try to use the following code to detect if the part is there…

if workspace:FindFirstChild("Plate") then
-- code
end

AND/OR

if workspace:IsAncestorOf(Plate) then
-- code
end

… It doesn’t run the code on scenarios where the plate is there. In summary, the plate doesn’t tween away when it already exists, so I end up with a bunch of plates. To better understand the issue, below I have linked some resources:


CODE: LocalScript, located in ReplicatedFirst.

local rps = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local ts = game:GetService("TweenService")
local food = rps:WaitForChild("Food")
local plate = food.Plate
local bread = rps.Food.Bread
local meat = rps.Food.Meat
local lettuce = rps.Food.Lettuce
local tomato = rps.Food.Tomato
local MenuGui = player.PlayerGui:WaitForChild("MenuGui")
local playbutton = MenuGui.Background.Frame:WaitForChild("PlayButton")

local doneMakingBurger = false -- set to false
local partName = "Plate"
local foundPart = workspace:FindFirstChild(partName) -- should check if the part exists


print(player.PlayerGui.Parent.Name)
playbutton.MouseButton1Click:Connect(function()
	wait(.2)
	doneMakingBurger = true
end)
while true do
	wait(.01)
	if doneMakingBurger == true then
		doneMakingBurger = false
		
		if foundPart then
			local oldPlate = game.Workspace:WaitForChild("Plate") -- skips this part, not sure why
			local oldGoal = {}
			oldGoal.Position = Vector3.new(-45, 0.5, -31.224)
			local oldTweenInfo = TweenInfo.new(1.2, Enum.EasingStyle.Quad)
			local plateTweenOut = ts:Create(oldPlate, oldTweenInfo, oldGoal)
			plateTweenOut:Play()
			oldPlate:Destroy()
			
			local newPlate = plate:Clone()
			newPlate.Position = Vector3.new(45, 0.5, -31.224)
			newPlate.Anchored = true
			newPlate.Parent = game.Workspace
			local newGoal = {}
			newGoal.Position = Vector3.new(0, 0.5, -31.224)
			local newTweenInfo = TweenInfo.new(1.2, Enum.EasingStyle.Quad)
			local plateTweenIn = ts:Create(newPlate, newTweenInfo, newGoal)

			plateTweenIn:Play()
		else
			local newPlate = plate:Clone()
			newPlate.Position = Vector3.new(45, 0.5, -31.224)
			newPlate.Anchored = true
			newPlate.Parent = game.Workspace
			local newGoal = {}
			newGoal.Position = Vector3.new(0, 0.5, -31.224)
			local newTweenInfo = TweenInfo.new(1.2, Enum.EasingStyle.Quad)
			local plateTweenIn = ts:Create(newPlate, newTweenInfo, newGoal)

			plateTweenIn:Play()
			doneMakingBurger = false
			
			for i = 5, 0, -1 do -- added a countdown that will show up in the output to check if the script detects the new plate
				print(i)
				wait(1)
			end
			doneMakingBurger = true
		end
	end
	
	-- plate present pos (tween to) 0, 0.5, -31.224 (vector)
	-- plate before pos (tween from) 45, 0.5, -31.224
end

YT Video linked to this text:


Any input/help is appreciated. I have tried doing research to no avail. I appreciate everyone’s time!

(If you feel like doing a little extra or don’t know the solution and still want to help, I would also appreciate some feedback on how I’m formatting my scripts. Let me know if it’s too spaced out, has good readability, etc. Thank you for your feedback!)

I think the issue is that you are checking if the plate exists when the script starts and that variable is never changed. Insert foundPart = newPlate after setting the parent of newPlate.

Also i got bored and am now watching all the videos on your yt lol

Haha I just realized I still have stuff on my channel from years ago lol. I really thought I would be a youtuber :sob: anyways, Thank you so much for your help! It ended up working and I appreciate it. The only thing is that after the plate tweens off the screen and another one tweens back in, the cycle doesn’t repeat. I may be missing something really small, but if you could help that’d be great!

I think it might be an issue with how “oldPlate” is named the same as the default plate. A simple fix would be to do newPlate.Name = "NewPlate" before setting the parent of it.

Also, you may have not set foundPart = newPlate in the first section of the if statement where you create the newPlate.

Also also, you may want to use a function to tween in the plate since you reuse the same code in both sections of the if statement.

Spotted a few issues in this code.

local oldPlate = game.Workspace:WaitForChild("Plate") -- skips this part, not sure why

It most likely skips this because foundPart is never true. Assuming local foundPart = workspace:FindFirstChild(partName) doesn’t equal nil (you should be using :WaitForChild() to ensure it is found), then it will be nil, which is why it is “skipping” this. It also does not delete any plates as it goes to the else section of the if statement (which is why you end up with a bunch of plates).

local plateTweenOut = ts:Create(oldPlate, oldTweenInfo, oldGoal)
plateTweenOut:Play()
oldPlate:Destroy()

This tween never gets played. You play the tween, then instantly delete the part that gets tweened. You should wait for the plate to finish tweening using .Completed:Wait()

Also, :WaitForChild() in a loop isn’t good practice. That while loop runs every .01 seconds, you are yielding for a plate that might not exist. Use :FindFirstChild() instead.

Fixed code:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local TweenService = game:GetService("TweenService")

local Food = ReplicatedStorage:WaitForChild("Food")
local Plate = Food:WaitForChild("Plate")
local Bread = Food:WaitForChild("Bread")
local Meat = Food:WaitForChild("Meat")
local Lettuce = Food:WaitForChild("Lettuce")
local Tomato = Food:WaitForChild("Tomato")

local menuGui = LocalPlayer.PlayerGui:WaitForChild("MenuGui")
local playButton = MenuGui.Background.Frame:WaitForChild("PlayButton")

local doneMakingBurger = false

--// Simple Tween Function to clean up the while loop
local function tweenPlate(object, startPosition, endPosition, duration)
	object.Position = startPosition
	object.Anchored = true
	object.Parent = workspace

	local tweenInfo = TweenInfo.new(duration, Enum.EasingStyle.Quad)
	local tween = TweenService:Create(object, tweenInfo, {Position = endPosition})
	return tween
end

playbutton.MouseButton1Click:Connect(function()
	task.wait(0.2) --/ Use task.wait() instead of wait(), as wait() is depricated
	doneMakingBurger = true
end)

--// Main loop
while true do
	task.wait(0.01)
	if doneMakingBurger then
		doneMakingBurger = false

		local existingPlate = workspace:FindFirstChild("Plate") --/ FindFirstChild() instead of WaitForChild(), no yielding for missing parts
		if existingPlate then
			local tween = tweenPlate(existingPlate, existingPlate.Position, Vector3.new(-45, 0.5, -31.224), 1.2)
			tween:Play()
			tween.Completed:Wait() --/ Waits for the tween to complete, then delete it
			existingPlate:Destroy()
			local newPlate = plate:Clone()
			local newPlateTween = tweenPlate(newPlate, Vector3.new(45, 0.5, -31.224), Vector3.new(0, 0.5, -31.224), 1.2)
			newPlateTween:Play()
		else
			local newPlate = plate:Clone()
			local tween = tweenPlate(newPlate, Vector3.new(45, 0.5, -31.224), Vector3.new(0, 0.5, -31.224), 1.2)
			tween:Play()
		end
	end
end

Sorry if this doesn’t work exactly, its 4am and this is completely untested.

I’ve got other recommendations about your formatting and general code writing if you would like it but I dont want to pile everything on you at once :slight_smile:

Thank you, I have tested it out and it’s not working, but I do think that may be the issue. This is a remade project and I just realized I ran into the same issue with the names, so I think I would have to play around with that until I figure it out.

I also made sure to set foundPart = newPlate in the first part of the if statement.

Additionally, thank you for the recommendation on the functions, I do need to work on using them when needed. I appreciate it!

Okay thank you so much for your feedback! I will work it into my code and let you know how it goes.

Also I would greatly appreciate any feedback you have on my code formatting. I’m open to any constructive criticism or recommendations.

I just wanted to say thank you for your time to write this out as well.

I didn’t reformat your code how I would write it but for general advice:

  1. Use camelCase for variables; Ex: local veryCoolVariable
  2. Use PascalCase for functions; Ex: function VeryCoolFunction()
  3. Use PascalCase for roblox services;
    Ex: local TweenService = game:GetService("TweenService")
  4. Use uppercase SNAKE_CASE for configuration/variables that don’t need to be changed in the script, usually placed near the top of the script and then referenced in other places
    Ex: local PLAY_BUTTON_WAIT = 0.2 or local PLATE_TWEEN_TIME = 1.2
  5. Never make variables withnamesthathavenocapitalization
  6. Place comments throughout your script, you basically can never have too many comments
  7. Add spaces between parts of your script that do different things. Like comments, adding a bunch is ok

There’s many more examples such as using PascalCase for classes but the list would take forever.

Basically, do what @oo6j did in that example. I would consider that well formatted code. The only things I would change are changing the function to PascalCase and the food to be camelCase. Also, I’ve never seen anyone do comments like --//, is that a thing you took from javascript/others?

You need to go to sleep first though.

Okay thank you so much for the feedback! I’ll try and get those habits. I appreciate that you spent your time helping on my post.

Just finished testing out the code and it works. Thank you so much for your help! I do have a question though.

local tween = tweenPlate(newPlate, Vector3.new(45, 0.5, -31.224), Vector3.new(0, 0.5, -31.224), 1.2)

In the code above, are you just changing the parameters of the function, which in turn changes the tween information? And how does this code above get the Tween from the function? Thank you so much for your time regardless of whether you respond or not.

I also just realized the issue of why my original script wasn’t repeating. I somehow had mistakenly put the loop below in the else statement. Since the else only repeated the first time, it only counted down and changed doneMakingBurger to true the first time.

A tween is just a variable you can move around anywhere. In @oo6j’s example the “tweenPlate” function creates a new tween that is then returned from the function. The returned tween can then be run after that.

That probably doesn’t make an sense though so here’s an example:

-- Returning a number for a variable to use
local function GetARandomNumber()
	return math.random(1, 10) -- Return a random number from 1 to 10
end

local randomNumber = GetARandomNumber()
-- randomNumber is now equal to a random number from 1 to 10

---------------------------------------------------------------------------
-- Returning a tween object
local function GetATween()
	local tween = TweenService:Create(--[[<insert stuff here>]])
	
	return tween -- Instead of returning a random number, it now returns a tween object
end

local tween = GetATween()
-- tween is now equal to the tween created in the function, so you can use it now outside the function
tween:Play() -- This works!

You can also send parameters into the function which are used to change how the tween object is built.

Wow I didn’t know this, thanks for explaining and adding examples. This helped me understand the code a lot more. Again, thanks for your time!