godot4自定义按钮,适配boxcontainer中放置

godot4自定义按钮,适配boxcontainer中放置

实现代码如下:

extends Button
class_name CustomButton

@export var texture:Texture
@export var texture_image_count:int
@export var reload:bool = true :
	set(value):
		reload = value
		_setTexture()
	get:
		return reload
	
	
func _ready():
	_setTexture()


func _process(_delta):
	if(reload):
		_setTexture()

func _setTexture():
	if texture == null:
		return
	add_theme_stylebox_override("normal", _getOneImageInTexture(0))
	if texture_image_count >= 3:
		add_theme_stylebox_override("pressed", _getOneImageInTexture(1))
		add_theme_stylebox_override("hover", _getOneImageInTexture(2))
	else:
		add_theme_stylebox_override("pressed", StyleBoxEmpty.new())
		add_theme_stylebox_override("hover", StyleBoxEmpty.new())	
	
	if texture_image_count == 4:
		add_theme_stylebox_override("disabled", _getOneImageInTexture(3))
	else:
		add_theme_stylebox_override("disabled", StyleBoxEmpty.new())

	add_theme_stylebox_override("focus", StyleBoxEmpty.new())
	
	var width = texture.get_width() / texture_image_count	
	var height = texture.get_height()	
	size = Vector2(width, height)
	custom_minimum_size = Vector2(width, height)
		
func _getOneImageInTexture(number):
	var width = texture.get_width() / texture_image_count
	var height = texture.get_height()
	var style_box_texture = StyleBoxTexture.new()
	style_box_texture.texture = texture;
	var x = number * width
	style_box_texture.region_rect = Rect2(x, 0, width, height)
	return style_box_texture

界面添加自定义按钮:
在这里插入图片描述
运行效果:

在这里插入图片描述