C# - How to return a nullable transform?

Hi, I asked a question about returning the position of a vector3, but the solution isn’t working for me when returning a transform node instead.

Here is the code I’m trying to use:

public static Transform? GetEnemyTargetRay()
{
	RaycastHit hit;
	Ray ray = (Camera.main.ScreenPointToRay(Input.mousePosition));
			
	if (Physics.Raycast(ray, out hit) && hit.transform.tag == "Enemy")	return enemyTarget;
	{
		Transform enemyTarget = hit.transform;
		return null;
	}
}

The error is saying:

The type `UnityEngine.Transform' must be a non-nullable value type in order to use it as type parameter `T' in the generic type or method `System.Nullable<T>'.

I’ve googled the error and haven’t been able to make sense of any of the responses, most don’t come near to my situation. I hope it’s a simple fix and just something I’m missing, because I really can’t find out what it’s wanting me to do.

Since this isn’t a generic function (or you copied it wrong) i guess the class is a generic class. The code you provided here doesn’t deal with your generic parameter “T”, so the error isn’t in this function. It would help to see the actual code that produces the error

Some additional things:

  • There’s a question mark behind Transform. Is this a typo or why is it there?
  • Your if clause looks a bit strange. I will rearrange it how it is actually evaluated:

Your code:

if (Physics.Raycast(ray, out hit) && hit.transform.tag == "Enemy")
    return enemyTarget;
{
   Transform enemyTarget = hit.transform;
   return null;
}

As you can see there are some things wrong. First your code block is useless because it just comes after the if statement and isn’t related to the if at all. Next thing is you return the variable enemyTarget which doesn’t exist at this point. Last thing if the raycast fails the hit structure won’t be set, so you shouldn’t access it outside the if

I guess it should look like this:

public static Transform GetEnemyTargetRay()
{
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit) && hit.transform.tag == "Enemy")
    {
        return hit.transform;
    }
    return null;
}

But again, that isn’t relevant for the error you described.