I am creating a RTS game right now but at the selection localscript, The variable that was supposed to set itself to the unit makes my code think that its still nil.
Here’s the script:
--Services and Mouse
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
--Modules & Remotes
local Modules = game.ReplicatedStorage.Modules
local Remotes = game.ReplicatedStorage.RemoteEvents
--Requires
local UnitManager = require(Modules.UnitManager)
--Script
local SelectedUnit = nil
Remotes.AddSelectedUnit.OnClientEvent:Connect(function(unit)
local CheckifUnit = unit:FindFirstChild("isselected")
if CheckifUnit then
SelectedUnit = unit
else
warn("COULD NOT SELECT, NOT A UNIT.")
end
print(SelectedUnit)
end)
Mouse.Button1Down:Connect(function()
if not SelectedUnit == nil then
local mousepos = Mouse.Hit.p
UnitManager.MoveUnit(SelectedUnit,mousepos)
else
print("No unit selected.")
end
end)
Oh, then keep it as is. But, change the Script to this
Remotes.AddSelectedUnit.OnClientEvent:Connect(function(unit)
local CheckifUnit = false
if unit then
CheckifUnit = unit:FindFirstChild("isselected")
end
if CheckifUnit then
SelectedUnit = unit
else
warn("COULD NOT SELECT, NOT A UNIT.")
end
print(SelectedUnit)
end)
The unary operator not has higher precedence than the variable SelectedUnit therefore it’s (not SelectedUnit) == nil.
Because not returns a boolean, this section of code will always result in false as x == nil can only result in true if x is nil.
Because of all this you’d probably mean not (SelectedUnit == nil) so you might want to put a parenthesis around SelectUnit == nil to if it solves your issue, or use SelectedUnit ~= nil instead.