Education_Lesson Plans
Reusing Code with script.Parent (코드 재사용)
Roblox_개발자
2021. 4. 19. 14:26
education.roblox.com/en-us/resources/intro-to-game-design-coding-1-reusing-code-with-script-parent
script.Parent로 코드 재사용하기
이 플랫폼은 사용자 경험을 개선하고, 콘텐츠를 맞춤 설정하고, 소셜 미디어 기능을 제공하고, 트래픽을 분석하기 위해 쿠키를 사용합니다. 이 플랫폼의 쿠키 사용을 중지 또는 관리하는 방법
education.roblox.com
Intro to Coding and Game Design
전 시간에 part들의 색상을 반복문을 이용하여 계속 변경되도록 구현하였습니다. 그런데 이 색상 변경하는 것을 다른 part들에게 적용하고 싶어 졌습니다. 그래서 색상이 변경되는 part의 이름이 같은 또 다른 part를 만들어 봤지만 아쉽게도 작동하지 않습니다.
그러면 각 part 마다 script를 짜줘야 할까요? 정답은 아닙니다! (처음에 네이밍 해준 part만 바뀌게 됩니다.)
코드를 재사용할 수 있는 방법에 대해서 알아보죠.
-- Changes the color of loopingPart every few seconds
-- Create a variable to store the part
local loopingPart = game.Workspace.LoopingPart
-- Looping Code
while true do
-- Changes loopingPart's color
loopingPart.BrickColor = BrickColor.new(0.7, 0.9, 0.9)
-- Wait 3 seconds before next instruction
wait(3)
loopingPart.BrickColor = BrickColor.new(0.9, 0.4, 0.9)
wait(3)
loopingPart.BrickColor = BrickColor.new(0.4, 0.5, 0.4)
wait(3)
end
Making the Script Reusable
-- Changes the color of loopingPart every few seconds
-- Create a variable to store the part
local loopingPart = script.Parent
-- Looping Code
while true do
-- Changes loopingPart's color
loopingPart.BrickColor = BrickColor.new(0.7, 0.9, 0.9)
-- Wait 3 seconds before next instruction
wait(3)
loopingPart.BrickColor = BrickColor.new(0.9, 0.4, 0.9)
wait(3)
loopingPart.BrickColor = BrickColor.new(0.4, 0.5, 0.4)
wait(3)
end
위에 코드는 'game.Workspace.LoopingPart'로 오직 LoopingPart으로 명명된 Part만 색상이 변경되게 됩니다.(또 다른 LoopingPart라는 Part를 생성하더라도 처음 것만 색상이 변경되게 됩니다.) 그래서 어느 Part들을 제어하기 위해서 'script.Parent'라는 녀석을 사용하게 됩니다. 이 명령은 개체가 연결된 모든 개체를 저장합니다. 이 경우 스크립트가 Part에 첨부된 경우입니다.
Parents and Children
Parents - Children 의 관계를 나타내고 있습니다.
위 사진을 통해 ColorPart는 Parent, ColorChangeScript는 Child라는 것을 보이고 있습니다.
코드 'script.Parent'를 해석하면 script의 Parent 즉 Part를 찾으라는 겁니다. 이 코드를 통해 Part의 이름을 몰라도 우리는 해당 Part를 참조(refer)할 수 있게 되었습니다.
Duplicate and Test Parts