Question, how would I change the image of a UI

I’m Trying to make some UI that the image changes Every time the UI gets pressed, Here’s an example:

local Button = script.Parent

Button.TouchTap:Connect(function()
    local Chance = math.random(1,5)
	if Chance >= 4 then
		--Image One Here
	elseif Chance >= 3 then
		--Image Two Here
	else
		--Image Three Here
	end
end)

Thank You, anything helps.

1 Like

Quite simple. To make sure all images are properly preloaded, I’d have multiple image objects and display/hide them.

The following example is fairly similar to your sample, except I placed the images in a table, and random number represents a random index with image as the value.

local frame = script.Parent:WaitForChild("Frame")
local button = frame:WaitForChild("TextButton")

-- images in order
local images = {
	frame:WaitForChild("Image1"), frame:WaitForChild("Image2"),
	frame:WaitForChild("Image3"), frame:WaitForChild("Image4")
}

local RandomGen = Random.new()

local currentImg = images[1] -- first image
currentImg.Visible = true

button.Activated:Connect(function()
	local randomNum: number
	repeat
		-- prevent duplicates
		randomNum = RandomGen:NextInteger(1, #images)
	until images[randomNum] ~= currentImg
	
	currentImg.Visible = false
	currentImg = images[randomNum]
	currentImg.Visible = true
end)

UI structure:

image

If you are looking for a single image, you could take the same path and store rbxassetid://s in the table, and set the ImageId instead of switching current image with a new one and modifying visibility. However, the images could flicker the first time you use them, so you may want to use ContentProvider to preload them.

local frame = script.Parent:WaitForChild("Frame")
local button = frame:WaitForChild("TextButton")
local image = frame:WaitForChild("ImageLabel")

local imageIds = {
	"rbxassetid://", "rbxassetid://", "rbxassetid://", "rbxassetid://"
}

local RandomGen = Random.new()

local currentId = imageIds[1]

button.Activated:Connect(function()
	local randomNum
	repeat
		randomNum = RandomGen:NextInteger(1, #images)
	until imageIds[randomNum] ~= currentId
	
	image.Image = imageIds[randomNum]
end)

Also, I made the TextButton transparent, removed the text, and placed it over the images. Its Z-index has to be high enough to position the button in front of all the image labels.

1 Like