Jump to content

[AJUDA] Problemas com GUI.


Recommended Posts

Olá, estou com dificuldades em algumas situações referente ao GUI.

1. Tentei utilizar o if (botao == "left") then mas acabou que nenhum botão executava a função;

2. Tento utilizar o elemento button na segunda função, mas não consigo (Expected element at argument 2, got nil);

3. Quando clico na caixa de texto para digitar o texto ele envia o texto, sem ao menos me esperar digitar, ele envia no outputChatBox o que estava pré-definido.

function openButton()

	if (getElementData(localPlayer, "opennedButton")) then
		outputChatBox("| ERRO | O botão já está aberto.")
	else
		outputChatBox("Você abriu o botão.")
		setElementData(localPlayer, "opennedButton", true)
		showCursor(true)
		botao = guiCreateButton(0.5, 0.5, 0.09, 0.05,"Enviar mensagem", true)
		botaoedit = guiCreateEdit(0.59, 0.5, 0.15, 0.05, "Escreva uma mensagem aqui.", true)
		guiEditSetMaxLength(botaoedit, 37)
end
end
addCommandHandler("abrirbotao", openButton)

function breakButton()

	setElementData(localPlayer,"opennedButton", false)

end
addCommandHandler("tirar", breakButton)

function onClickButton(button)
  
  if (botao == "left") then

	guiSetVisible(botao, false)
	guiSetVisible(botaoedit, false)
	showCursor(false)
	setElementData(localPlayer, "opennedButton", false)
	texto = guiGetText(botaoedit)
	outputChatBox(texto)

	end
  end
addEventHandler("onClientGUIClick", button, onClickButton)

Obrigado pela atenção e compreensão de todos.
Quem puder me ajudar irá receber Thanks!

Edited by GM_Goulart
Em if (botao == "left") estava com (botao == left) sem aspas, coloquei-as.
Link to comment
  • Other Languages Moderators

Na terceira função, não é if (botao == "left") then e sim if (button == "left") then, pois foi oq vc definiu nos parâmetros da function. (o que vc definiu dentro do parênteses após o nome da function.)

O addEventHandler ("onClientGUIClick") sempre dará erro, pois vc está tentando adicionar uma função de clique antes de criar o botão. O botão será criado somente depois quando aquela primeira função for chamada. Para resolver isso vc tem 2 opções.

  1. Mover o addEventHandler para dentro daquela primeira função, depois de criar o botão. E em vez de usar button no segundo argumento, use botao no lugar.
  2. Manter o addEventHandler ali fora mas sem definir um botão específico. Dai use guiRoot no lugar de button. Dessa forma a função ativará ao clicar em qualquer guiCreateButton deste resource. E então dentro dessa função vc pode verificar if (source == botao) then para fazer funcionar somente no botão específico.
Edited by Lord Henry
  • Thanks 1
Link to comment
  • Moderators

Fora os erros mencionados acima, você também pode evitar esse setElementData que de forma desnecessária vai utilizar rede para atualizar no servidor. Em vez disso você pode usar uma simples variável como a do próprio botão.

A função 'openButton' deveria ficar assim:

function openButton()
	if botao then
		outputChatBox("| ERRO | O botão já está aberto.")
	else
		outputChatBox("Você abriu o botão.")
		showCursor(true)
		botao = guiCreateButton(0.5, 0.5, 0.09, 0.05,"Enviar mensagem", true)
		botaoedit = guiCreateEdit(0.59, 0.5, 0.15, 0.05, "Escreva uma mensagem aqui.", true)
		guiEditSetMaxLength(botaoedit, 37)
		
		addEventHandler("onClientGUIClick", botao, onClickButton, false)
		-- use 'false' depois da função se o evento for adicionado só para 1 único elemento
	end
end
addCommandHandler("abrirbotao", openButton)

E o comando de 'tirar':

function breakButton()
	
	if botao and isElement(botao) then -- verificar se existe o botão, isto é, ele está na tela
	
		destroyElement(botao) -- remover elemento
		destroyElement(botaoedit)
		botao = nil -- limpar referência na memória
		botaoedit = nil
		showCursor(false)
		
		outputChatBox("Botão e edit removidos")
	else
		outputChatBox("Erro: O Botão não está na tela, use /abrirbotao")
	end
end
addCommandHandler("tirar", breakButton)

Função do "onClientGUIClick":

function onClickButton(button)
  
	if (button == "left") then -- aqui se refere ao botão do mouse que vc clicou, não o botão do jogo
	
		showCursor(false)
		local texto = guiGetText(botaoedit)
		if texto == "" then -- essa condição verifica se o campo de edição está vazio, se sim notifica o jogador
			return outputChatBox("Digite algum texto!")
		end
		outputChatBox(texto)
    
		destroyElement(botao)
		destroyElement(botaoedit)
		-- vc também pode usar source aqui, a 'source' deste evento é o elemento da GUI clicado, neste caso, o botão
		botao = nil
		botaoedit = nil
		--[[ Em vez de fazer sumir o botão/edit, irei destruir os elementos,
			vc pode optar por isso quando por exemplo criar poucos elementos cegui e quiser uma otimização
		]]

	end
end

(leia os comentários pelo código)

(código não-testado)

  • Thanks 1
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...