Can you use? game.Players:GetPlayerFromCharacter() ,Because,i want to change the Player's Character Model
To get the player's character from a LocalScript, first we have to index Players.LocalPlayer
, to get the LocalPlayer. You can skip this step if you already have a reference to the LocalPlayer..
local PlayersService = game:GetService("Players") local LocalPlayer = PlayersService.LocalPlayer
Then, we have to index its Character
property to find the character.
-- Get LocalPlayer.Character local Character = LocalPlayer.Character
There's a problem though. LocalPlayer.Character
could possibly be nil, so we have to use an ternary operator so that if it's nil, we wait on the CharacterAdded event to get the character then. So that code would be replaced with:
-- Get character, and if it's nil then wait for new character local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
Second problem: according to the wiki,
LocalScripts that are cloned from StarterGui or StarterPack into a player’s Backpack or PlayerGui are often run before the old Character model is deleted. Player.Character still refers to a model, but that model’s parent is nil and it is has been destroyed. Because of this, if the Character already exists, you should check to make sure that the Character’s parent is not nil before using it.
( from here ) Now we use another ternary operator, so that if there is a Player.Character, but it has a parent of nil, then we wait on CharacterAdded.
-- Get character, and if it's nil or its parent is nil then wait for new character local Character = ((LocalPlayer.Character and LocalPlayer.Character.Parent) and LocalPlayer.Character) or LocalPlayer.CharacterAdded:Wait()
So, the full code would be:
local PlayersService = game:GetService("Players") local LocalPlayer = PlayersService.LocalPlayer -- Get character, and if it's nil or its parent is nil then wait for new character local Character = ((LocalPlayer.Character and LocalPlayer.Character.Parent) and LocalPlayer.Character) or LocalPlayer.CharacterAdded:Wait()
This combination of ternary operators basically means: if LocalPlayer.Character exists and LocalPlayer.Character.Parent is not nil, then return LocalPlayer.Character, else wait on CharacterAdded