Change Material in script


I keep looking through documentation and on YT but cant find an answer not sure if its possible.

I'm trying to trigger an event where the material will change on an object in game.
any ideas?

thank you in advance


I have fiddled around with something like this last week. I took a few hours to figure most of this out but in the end the Materials can be changed via script.

So in my example there is a Cube with a Trigger which will act like a button to initiate the Material change. Inside this trigger I added a Sphere as an Object Reference which we can directly call up to change the material.

Now the Script inside the trigger:

local trigger = script.parent
local Sphere = script:GetCustomProperty("Sphere"):WaitForObject()

function OnBeginOverlap(theTrigger, player)
    if player and player:IsA("Player") then
		if Sphere then
			local Material = Sphere:GetCustomProperty("Material") -- notice here that the new "Material" is already saved inside the Sphere, this time using an Asset Reference to the "Amethyst" material to change it to.
			local MaterialSlots = Sphere:GetMaterialSlots() -- as objects can have more than one material slot, I get them all and run through them in a loop.
			for _, Item in ipairs(MaterialSlots) do
				Item.materialAssetId = Material -- this sets all material slots in the object to the new "Material" Asset Reference


Here is how I saved the new Material inside the Sphere:

Keep in mind that Objects with more advanced materials like the BookCase, etc, you will have to make sure about which Material Slot you want to change before changing the Material. In this case, you can do something like this instead:

local MaterialSlots = Sphere:GetMaterialSlots()
MaterialSlots[1].materialAssetId = Material

Or if you are looking to use a Custom Material, you can do the following:

Item.materialAssetId = "F04F36986AF1FD13:Custom Amethyst" -- or whatever your MUID of the Custom Material is.

I hope this answers your question. Feel free to let me know if you need any more help :slight_smile:

I have also published this to CC, just search for your name there.

API Link: MaterialSlot - Core Documentation

took abit of fiddling with but worked perfectly...THANK YOU!