Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Cannot cast from source type to destination type.

Discussion in 'Scripting' started by Sydious, Apr 18, 2015.

  1. Sydious

    Sydious

    Joined:
    Apr 1, 2010
    Posts:
    172
    I am having a hard time figuring out how my casting is wrong. Can someone help me figure this out?

    I have some sprite rigs built that consist of a EmptyGameObject and then SpriteRenderers for all the body parts of the rig as children.

    I need to iterate through all the sprite renderers and set the sorting layer for each one. I am getting the "Cannot cast from source type to destination type." but can't figure what I did wrong.

    Help?

    Code (JavaScript):
    1. var partyMember: GameObject[];
    2. var activeMember: int;
    3.  
    4.  
    5. function SetSortLayer(){
    6.  
    7.     var sprtRndrs_01 : SpriteRenderer[];
    8.     var sprtRndrs_02 : SpriteRenderer[];
    9.      
    10.     for(var i : int = 0; i < 7; i++){
    11.         sprtRndrs_02 = partyMember[i].GetComponentsInChildren(SpriteRenderer);
    12.         for (var rndr : SpriteRenderer in sprtRndrs_02) {
    13.             rndr.sortingLayerName = "Character_02";
    14.         }
    15.     }  
    16.  
    17.     sprtRndrs_01 = partyMember[activeMember].GetComponentsInChildren(SpriteRenderer);
    18.     for (var rndr : SpriteRenderer in sprtRndrs_01) {
    19.         rndr.sortingLayerName = "Character_01";
    20.     }
    21.  
    22. }
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    GetComponentsInChildren returns Component[], unless you use the generic version.

    Code (javascript):
    1. GetComponentsInChildren.<SpriteRenderer>()
    --Eric
     
    MD_Reptile likes this.
  3. Sydious

    Sydious

    Joined:
    Apr 1, 2010
    Posts:
    172
    Perfect! Thank you.
     
  4. Sydious

    Sydious

    Joined:
    Apr 1, 2010
    Posts:
    172
    So what is the difference between using GetComponentsInChildren.<SpriteRenderer>() vs GetComponentsInChildren(SpriteRenderer)? I see that since Unity5 this code gets flagged as needing to be changed and the editor will change those over sometime and sometimes not. Guess I don't understand the difference.
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The generic version returns SpriteRenderer[], the non-generic version just returns Component[].

    --Eric