How do you check if a part name exists already? Like how would you create a loop that would constantly run until it finds a part with the name that I want already, but then it checks again if the name I want to change the part to also exists without hardcoding a loop like 50 times. I keep trying to logic through this but then I get stumped and im back to square one.
01 | --What i'm trying to do |
02 |
03 | local part = Instance.new( "Part" , game.Workspace) --Part we will be checking to see if it exists |
04 | part.Name = "IAmAPart" --The parts name |
05 |
06 | local anotherPart = Instance.new( "Part" , game.Workspace) --The other part that will also have the same name |
07 | anotherPart.Name = "IAmAPart" --This new part is also named the same as the first part we created in the beginning of the script |
08 |
09 | for i,v in ipairs (game.Workspace:GetChildren()) do --Iterate through all the parts in the workspace |
10 | if v:IsA( "BasePart" ) then |
11 | if v.Name = = part.Name then --Hey, these two parts have the same name! |
12 | part.Name = "IAmAnotherPart" --No more name conflicts! Huzzah! |
13 | end |
14 | end |
15 | end |
But what if something like this happens...
01 | --What i'm trying to do |
02 |
03 | local part = Instance.new( "Part" , game.Workspace) --Part we will be checking to see if it exists |
04 | part.Name = "IAmAPart" --The parts name |
05 |
06 | local anotherPart = Instance.new( "Part" , game.Workspace) --The other part that will also have the same name |
07 | anotherPart.Name = "IAmAPart" --This new part is also named the same as the first part we created in the beginning of the script |
08 |
09 | local theThirdWheel = Instance.new( "Part" , game.Workspace) --Oh wait, another part? |
10 | theThirdWheel.Name = "IAmAnotherPart" --But its named what I want to change the first one to... |
11 |
12 | for i,v in ipairs (game.Workspace:GetChildren()) do --Iterate through all the parts in the workspace |
13 | if v:IsA( "BasePart" ) then |
14 | if v.Name = = part.Name then --Hey, these two parts have the same name! |
15 | part.Name = "IAmAnotherPart" --This will clear up the naming conflict with the first two parts, but now the first and third have a naming conflict! |
You would have that script while defining the part. To elaborate:
01 | local part = Instance.new( "Part" ) |
02 | part.Parent = workspace |
03 | part.Name = "IAmAPart" |
04 |
05 | local anotherPart = Instance.new( "Part" ) |
06 | anotherPart.Parent = workspace |
07 | if workspace:FindFirstChild( "IAmAPart" ) then |
08 | anotherPart.Name = "IAmAnotherPart" |
09 | else |
10 | anotherPart.Name = "IAmAPart" |
11 | end |