So I am trying to make a 2d platformer where the character can change colour by pressing certain keys. I am currently trying to figure out how to find the character as game.Players.LocalPlayer.Character says it's a nil value. I then went to the Dev Hub and found the character page. I changed to a local script and changed to player.Character and still no luck as player is unknown. Here is a small part of the code I am working with:
1 | if player.Character.Head.BrickColor = = BrickColor.new( "Really red" ) then |
2 | script.Parent.BrickColor = BrickColor.new( "Really red" ) |
3 | end |
I also have the code in a LocalScript inside of a Part in workspace. Any sort of help would be appreciated!
You cannot put a LocalScript in a part in workspace. Put the LocalScript in StarterPack and define part (e.g. local Part = game.Workspace.Part). The Player can be called by LocalScript in StarterPack using game.Players.LocalPlayer or script.Parent.Parent. Also if you want to detect a player's head color, you cannot use BrickColor.new("really red") because the color is not changed.
1 | if player.Character.Head.BrickColor then |
2 | script.Parent.BrickColor = BrickColor.new( "Really red" ) |
3 | end |
Let me explain the code above and why is it like that. So i assumed you have already set the player's head color to really red, or maybe you are going to change it in a script. If you did not, you will have to change the player's head color yourself. So explanation: if the player's head color is "Really Red" (if player.Character.Head.BrickColor then), then the Part's color will change, does that make sense to you?
This is simple! Just use this!
1 | for i,v in pairs (game.Players:GetChildren()) do |
2 | if v.Character and v.Character:FindFirstChild( "Head" ) then |
3 | { CODE } |
4 | end |
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. You're supposed to do:
1 | if not character or not character.Parent then |
2 | character = game.Players.LocalPlayer.CharacterAdded:wait() |
3 | end |
Then you define character after the if statement. I hope this helps :)