Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

Out parameter for GetComponent() and friends

Discussion in 'Experimental Scripting Previews' started by Ramobo, Nov 7, 2019.

  1. Ramobo

    Ramobo

    Joined:
    Dec 26, 2018
    Posts:
    212
    It would be useful for, say, raycasting.
    Code (CSharp):
    1. // Current method:
    2. if (Physics.Raycast(ray, out RaycastHit hit, 1f))
    3. {
    4.     Player player = hit.transform.GetComponent<Player>();
    5.  
    6.     if (player)
    7.     {
    8.         // ...
    9.     }
    10. }
    11.  
    12. // Or, using pattern matching:
    13. if (Physics.Raycast(ray, out RaycastHit hit, 1f))
    14. {
    15.     if (hit.transform.GetComponent<Player>() is Player player)
    16.     {
    17.         // ...
    18.     }
    19. }
    20.  
    21. // Proposed, a more elegant alternative to pattern matching:
    22. if (Physics.Raycast(ray, out RaycastHit hit, 1f))
    23. {
    24.     if (hit.transform.GetComponent(out Player player))
    25.     {
    26.         // ...
    27.     }
    28. }
    29.  
    30. // Like most such things, this can be easily extracted into an extension method, but would be nice to have officially:
    31. public bool GetComponent<T>(this Component component, out T t)
    32. {
    33.     T foundComponent = component.GetComponent<T>();
    34.  
    35.     t = foundComponent;
    36.  
    37.     return foundComponent; // This should work, since you can do `if (component)`. If not, cast?
    38. }
     
  2. M_R

    M_R

    Joined:
    Apr 15, 2015
    Posts:
    559
  3. Ramobo

    Ramobo

    Joined:
    Dec 26, 2018
    Posts:
    212
    Huh. Well, thank you. It's refreshing to come to the forum and not get ignored.
     
    Last edited: Nov 8, 2019
  4. Ramobo

    Ramobo

    Joined:
    Dec 26, 2018
    Posts:
    212
    Alright, two issues with this:
    1 - It was introduced in 2019.2. I'm stuck with 2019.1 for now.
    2 - This is only available for GetComponent(), but I need it for GetComponentInParent() too.
    Back to extension methods it is.
     
  5. Ramobo

    Ramobo

    Joined:
    Dec 26, 2018
    Posts:
    212
    Great. With extension methods, you can't use interfaces for that. Good luck writing good code in Unity. You need a workaround for even auto property serialization. Back to pattern matching it is. It's the shortest reliable method I could find.
     
  6. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,336
    I've had that extension method around forever, and it works just fine for interfaces. Code more, complain less.