Help getting Player in a server-script

Some context - I am making an RTS game and im currently trying to get the ‘units’ to attack other units. I know how to go about this but i’ve run into an issue because I cant and dont know how I would go about getting the player. It is important i get the player because there is owner values i need to check for, teams and other things.

Players.PlayerAdded() wouldn’t work with this because its multiple functions, ‘units’, and players all being handled with one script. I cant find any other ways to get the player. Are there any alternatives that could work?

What is the player that you want to get?

1 Like

If you want to communicate from client to server, use RemoteEvents. When a RemoteEvent is invoked, the player that invokes it is automatically passed as the first parameter, and you can use that in server script functions.

This is gonna run through an attack function every time a unit is in range of another team’s unit. I need to make sure the units attack the other team’s units and not the same team so I have to get the player’s team. I also need to check the owner

local function findNearestTarget(unit, plr)
	for i, v in ipairs(game.Workspace.Units:GetChildren()) do
		if v:IsA("Model") and v:FindFirstChild("Config") then
			if v.Config.Owner.Value ~= plr.Name then
				local dis = (unit.HumanoidRootPart.Position - v.HumanoidRootPart.Position).Magnitude
				if dis <= unit.Config.Range.Value then
					nearestTarget = v
				end
			end
		end
	end
	return nearestTarget
end

not related but this isnt final i need to do alot more ^^
Remoteevents/functions might work but i dont know how I would go about it.

1 Like

Make a local script for the player and call the function that’s in the Server Script by using a RemoteEvent instance…
Example:

LOCAL SCRIPT

remoteEvent = game:GetService("ReplicatedStorage").RemoteEvent
if (condition) then
    remoteEvent:FireServer(parameters) 
end

SERVER SCRIPT

 --@param first is always the local player who fires the event. All others send in whatever you want
game.ReplicatedStorage.RemoteEvent.OnServerEvent:Connect(function(localPlayer, parameters)
    local char = localPlayer.Character

    if localPlayer.Team == team and (check if character is within range of unit) then
        --do whatever
    end
end)
1 Like

Example; there are two units and two buildings on each team, yellow and red.
I want the units to attack the other team’s units and buildings, but not the same team. Red should attack yellow, yellow should attack red. Each unit and building has a team and owner in its config but I need to get the player to match those together, which is what i’m stuck on.

You could potentially use

game:GetService("Players"):FindFirstChild(v.Config.Owner.Value) --> Assuming v.Config.Owner.Value is a player name...
1 Like