Hello. I've been trying to make a script that increases a parts density by 0.1 every time someone clicks a button.
function onClicked() game.workspace.peer.CustomPhysicalProperties = PhysicalProperties.new(0.1,0,0) local tere = game.workspace.peer.CustomPhysicalProperties tere.value = tere.value+(0.1) end script.Parent.ClickDetector.MouseClick:connect(onClicked)
This is what I have come up with so as you can see I failed miserably. What would be the correct way? Thank you for your time!
There are two minor issues that are preventing the code from working. Firstly, it sets the Density to 0.1 every time that the button is clicked. We can fix this by moving the 2nd line to outside the click handler, so that it's only executed in the beginning of the script:
workspace.peer.CustomPhysicalProperties = PhysicalProperties.new(0.1,0,0) function onClicked() -- etc end script.Parent.ClickDetector.MouseClick:connect(onClicked)
The second issue is a bit more complicated to undestand, while its fix is quite simple. When answering questions, my primary goal is to help others understand the concepts, so I'll explain it briefly.
Consider the following line of code:
local tere = workspace.peer.CustomPhysicalProperties
This reads the CustomPhysicalProperties
property of the part, assigning its value to a local variable named tere
. Now tere
contains an immutable copy of that value. This means two things:
tere = "hello world"
, if you like. This has no effect on the underlying value, which could be discarded if it isn't used elsewhere.CustomPhysicalProperties
property of that part changes, the changes won't appear in tere
.The correct way to change the CustomPhysicalProperties
property for a part is assigning a value to it. For your use case, we must construct a new CustomPhysicalProperties
value using the previous value, like so:
local tere = workspace.peer.CustomPhysicalProperties workspace.peer.CustomPhysicalProperties = PhysicalProperties.new(tere.Density + 0.1, 0, 0)