C# - How to properly 'return' a Vector3 from this method?

Hi guys,

Extremely basic question here, basic enough that google doesn’t seem to want to provide me with the answer! I guess it is pretty much a ‘in this case’ rather than a global solution. I’m very new to C# so - baby words please :slight_smile:

I somewhat understand what return; does and I’m trying to use it to make a utilities file for actions that are repeated, my game will have many events where it needs to check what I am mousing over, so I don’t want to have to keep typing or pasting it out.

My understanding is that this code would return the position of what my mouse is hovering over, and my understanding is that I would need to return that position so I can, for example, type position = Utilities.Instance.GetTargetRay() and that will give me the pos. Any help appreciated.

public Vector3 GetTargetRay()
{
	RaycastHit hit;
	Ray ray = (Camera.main.ScreenPointToRay(Input.mousePosition));
	float hitDist = 0f;
	
	if (Physics.Raycast(ray, hitDist))	
	{
		Vector3 targetPoint = ray.GetPoint(hitDist);
		return targetPoint;
	}
	
}

There’s no instance information needed, so it can be static, and not bother with the Instance property.

public static Vector3? GetTargetRay() {
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

	if (Physics.Raycast(ray, out hit)) return hit.point;
	return null;
}

Using Nullable Types

public Vector3 GetTargetRay()
{
RaycastHit hit;
Ray ray = (Camera.main.ScreenPointToRay(Input.mousePosition));

    if (Physics.Raycast(ray, hit)) 
    {
       
       return hit.point;
    }
    return Vector3.zero;

}

In truth it isn’t ideal to return a Vector3 like this because you need a special case return value when nothing is hit - in this case I’m using Vector3.zero to indicate no hit. Functions which return a value must always return something.