Why this method returns me null?

Even if I set up the tags and have a waypoint without anything between me and him, it doesn’t return anything. Some help would be appreciated. Here’s the code:

GameObject findBetterWayPoint() {


	GameObject[] gos = GameObject.FindGameObjectsWithTag("wayPoint");

	GameObject closestGO = null;

	foreach(GameObject go in gos) {

		if((!Physics.Linecast(transform.position, go.transform.position))) {

			closestGO = go;



	if(closestGO == null) {

		closestGO = GameObject.Find("Player");


		return closestGO;

  • My tagged objects are Emptys, does this interfere in something?

Well the only reason your method returns null is

  • because GameObject array is empty
    (ie, FindGameObjectsWithTag returned
    an empty array) or there’s nothing that the linecast hit
  • You don’t have ane object named “Player” in your scene

if your GameObject is empty (which you seem to be suggesting) then the LineCast will never be made, as you will never enter the loop.

On a side note, because your foreach loop doesn’t make a lot of sense to me : you iterate through your objects and, if the line cast fail, you assign the go to the closestGo. Which mean that you will always have in closestGo either null or the last object that failed the cast (but that won’t necesseraly be the closest one btw).

So the problem is the generic Cube you’re using comes with a BoxCollider on it.
The linecast is hitting those colliders.

The easiest way to fix it is to remove the BoxCollider component from the cube. If you need that Collider for other reasons, then you’ll need to use layers. Put the Cube on a layer, and use the layermask variable in the Linecast to ignore that collider.

More info on layermasks here.

Ok. I could figure out that with the layer ‘Default’ active in where I want to be a wall, the LineCast/RayCast works. But, since yesterday everything with the layer ‘Default’ selected do not appear in my scene. If I have the object selected, I can see just his Wireframe in blue. In the game it appears, just in the scene I can’t see him. I already try to reinstall Unity but I do not get any result. Is it some config that I messed up with?

  • Also, if I click and drag the mouse, in order to select a lot of objects in the scene, my invisible ones do not get selected.