Raycast from agent to character trouble

im trying to make it so if my enemy sees the target OR if the target is within a certain range then they will chase them. it works when im withing the raycast or distance but if i just “run” the game instead of “play here” it spits out an error. any ideas?

Workspace.EnemyTest.Movement:71: attempt to index nil with ‘HumanoidRootPart’

local function canSeeTarget(target)
local origin = hrp.Position
local direction = (hrp.Position - target.HumanoidRootPart.Position).unit * 25
local ray = workspace:Raycast(origin, direction)

local hit, pos = workspace:FindPartOnRay(ray, Character)

if hit then
	if hit:IsDescendantOf(target) then
		return true
	end
else
	return false
end

end

Is your raycast looking for a player character? If so, “Run” on roblox studio only runs the server and does not initialize a client test. This would explain your issue since “Run” does not spawn a player and as such would not spawn their character, either.

1 Like

ohh! Good point! Let me test and see if it still happens with my player in the world.

so even with my character in the world it still gives the same error, even if i play test right in front of the enemy.

i can post the entire script, although this is the only part giving an error. also the only line that calls for this function is in a findTarget function. if distance < maxDistance or canSeeTarget() then which worked earlier but now doesnt for some reason

okay so i seem to have figured out whats causing it. the distance of the player from the enemy conflicts with the raycast logic i have. if distance < maxDistance or canSeeTarget() breaks because i had the distance set to 10 studs, OR if the enemy can see the player then chase. i tried switching things around and adding different logic to the line above but it still gives the same error. it seems i need to recreate the raycast logic i posted in the original posting.