Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Increase density by 0.1 after every click?

Asked by 5 years ago

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!

1 answer

Log in to vote
1
Answered by
gskw 1046 Moderation Voter
5 years ago

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:

  1. Immutable: the value itself can't be changed. You can still reassign the variable though, so you could do tere = "hello world", if you like. This has no effect on the underlying value, which could be discarded if it isn't used elsewhere.
  2. Copy: even if you were able to change the value, the changes wouldn't affect the part, as you're simply looking at a copy of the value. Conversely, if the 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)
0
Thanks for explaining admiral2001 36 — 5y
Ad

Answer this question