How to create a /givegun command?

So I am very new to Lua and fiveM. The only coding experience I have is with C# and SQL, that’s it. It’s helpful but doesn’t do the job. So I’ve been lurking around on the forum and google but couldn’t find a tutorial of what I want to do. I have no code or any game mode made yet. I’m just trying to experiment so that I can learn to program in lua/fiveM and eventually create a server.

Basically I want to create a command /givegun “gunname” and all it does is just give a gun they wrote with 9999 ammo. e.g. /givegun m4 will give them WEAPON_ASSAULTRIFLE with 9999 bullets (I know typing m4 won’t give weapon_assaultrifle, I will have to manually transform m4 to weapon_assaultrifle in code). I first tried with just /givegun and it would’ve given the assaultrifle with 500 ammo but that didn’t work either. It only succeeded my to give them guns when they spawn but that’s not what I need.

This is what i’ve tried:

Commands.lua (server_script)

TriggerEvent('es:addCommand', 'car', function(source, args, user)
    TriggerClientEvent("es_com:giveGun"), source, args[1])
    end)

ClientWeapon.lua (client_script)

  RegisterNetEvent("es_com:giveGun")
  AddEventHandler("es_com:giveGun", function(w)
        local ped = GetPlayerPed(-1)
        local weapon = GetHashKey(w)
        if weapon == nil then
            GiveWeaponToPed(ped, GetHashKey("WEAPON_ASSAULTRIFLE"), 5000, false))
        end
        GiveWeaponToPed(ped,GetHashKey(weapon), 5000, false))
      end, false)

I’ve tried it with RegisterCommand but couldn’t find a way either.
An extra problem I have atm is never knowning when to use things like: Source, args, user and such in function().
My excuses for lack of lots of knowledge. I’m just hyped to try run a server in FiveM. SA:MP days were glorious. Thank you!

In your server script, you have

TriggerEvent('es:addCommand', 'car', function(source, args, user)

change ‘car’ to ‘givegun’?

also, make sure in your __resource.lua script, you have Commands.lua and ClientWeapon.lua

Thank you lmao, I noticed it right after the notification and then checked your reply… Such a stupid mistake

Still not working :confused:

Here is a simple script… /givegun [name].

RegisterCommand("givegun", function(source, args, rawCommand)
	local playerPed = GetPlayerPed(-1)
	local weaponHash = GetHashKey(args[1])
	local ammoCount = 9999
	
	TriggerEvent("chatMessage", "", {0, 0, 0}, "Giving weapon")
	GiveWeaponToPed(playerPed, weaponHash, ammoCount, false)
end)

Also, essentialmode already has a command implemented for this. /giveweapon (iirc)

1 Like

Thank you very much!!! Now I know how some other stuff work too

1 Like

Where I put this script?

Does this help?

1 Like

2 years later
Please pay attention to post dates - there’s 0 need to revive dead topics like these just to promote your resource.