Locate a game object using rays


I need to check if a gameObject is in the cameras view or not. I have got that working, (On a basic level), with Renderer.IsVisible. Ok. But now I need a away to check if he is behind a tree, or behind an object. I believe the easiest way to do this, would be to use a ray.

I tried using line cast, but it didn’t work. It shot off in a different direction.

	    Debug.DrawRay(you.position, slenderMan.position, Color.green);
	if (!Physics.Linecast (you.position, slenderMan.position))
	Debug.Log("He is behind a collider");

The debug line was never called, because when I looked in the screen view, the ray (Shown in green) was pointing in a different direction.

Is there a way to fix this? As in, line cast to a specific object to detect colliders?


Is there a reason why you’re not using a raycast instead?

From my interpretation of the documentation you’re checking whether there is a collider between you and the target, it returns true if there is a collider.
So you should be getting a message saying that he is behind a collider when he isnt,

As for the odd error you’re getting, make sure the target or the origin of the ray isnt a child of something, as that might get you some odd results.

I’ve tried doing something similar myself, here’s the code i made:

public GameObject target;

	void Update () {
			Debug.Log("Hai World");

as it is written here the console prints “hai world” when there isnt a collider between the origin and the target.

Hope this helped :slight_smile: