I have a textlabel that needs to change text to the name of object in front of players cursor. The script perfectly prints the object that was raycasted but I can't get it to change text on the label.
local label = game.StarterGui.guistuff.WhatYouLookinAt local runservice = game:GetService("RunService") local function MouseRaycast() local mousePos = uis:GetMouseLocation() local mouseRay = cam:ViewportPointToRay(mousePos.X, mousePos.Y) local rayResult = workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 20) return rayResult end runservice.RenderStepped:Connect(function() local result = MouseRaycast() if result and result.Instance then local objname = result.Instance.Name label.Text = objname end end)
I believe I made a stupid mistake and I should be executed.
Problem
This is something I seen most people do. First you need to understand what StarterGui is. StarterGui is basically a container for all the GUIs in your game. When a Player joins the Server it will replicate all those GUIs in StarterGui to the Player's PlayerGui where it will be displayed for that player.
So the question is "How do I get the Player's PlayerGui?".
Solution
We can get the Player
local player = game:GetService("Players").LocalPlayer
The PlayerGui is the child of the Player
local player = game:GetService("Players").LocalPlayer local label = player:WaitForChild("PlayerGui"):WaitForChild("guistuff"):WaitForChild("WhatYouLookinAt")
I would rather use heartbeat instead of renderstepped.
Fixed code
local player = game:GetService("Players").LocalPlayer local label = player:WaitForChild("PlayerGui"):WaitForChild("guistuff"):WaitForChild("WhatYouLookinAt") local runservice = game:GetService("RunService") local raycastParams = RaycastParams.new() -- RaycastParams I think is short for raycastparameters, pretty self explanatory. raycastParams.FilterType = Enum.RaycastFilterType.BlackList --Setting filter type to blacklist raycastParams.FilterDescendantsInstances = {player.Character} -- filtering the descendants of the character. local function MouseRaycast() local mousePos = uis:GetMouseLocation() local mouseRay = cam:ViewportPointToRay(mousePos.X, mousePos.Y) local rayResult = workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 20, raycastParams) return rayResult end runservice.Heartbeat:Connect(function() local result = MouseRaycast() if result and result.Instance then local objname = result.Instance.Name label.Text = objname end end)
If the code doesn't work you can tell me.