Search Unity

Why I can't access stuffs more directly?

Discussion in 'Scripting' started by hkdtmer, May 25, 2015.

  1. hkdtmer

    hkdtmer

    Joined:
    Apr 2, 2014
    Posts:
    35
    Code (CSharp):
    1. //files have .bytes extension already
    2. //example 1: errors in runtime only
    3. var s = (TextAsset[])Resources.LoadAll("midi");        //InvalidCastException
    4. var s = Resources.LoadAll("midi") as TextAsset[];    //NullReferenceException
    5.  
    6. //OK
    7. var songs = Resources.LoadAll("midi");
    8. var s = (TextAsset)songs [i];
    9.  
    10. //example 2
    11. var txtText = GameObject.Find("TxtText").GetComponent<Text>().text;
    12. txtText = "abc";    //no error messages but the UI text string didn't change
    13.  
    14. var txtText = GameObject.Find("TxtText").GetComponent<Text>();
    15. txtText.text = "abc";    //OK
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Yup that's language features, not bugs.

    Your second example is an issue with value versus reference types. Google it.

    For the first example you should use the generic method. Faster and avoids casting issues.
     
    hkdtmer likes this.
  3. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    You can use the generic version of LoadAll
    Code (csharp):
    1. Resources.LoadAll<TextAsset>("midi");
    and BoredMormon beat me to it.
    Text.text is probably a property aswell, which also means you may or may not have assignment rights to it.
     
    hkdtmer likes this.
  4. hkdtmer

    hkdtmer

    Joined:
    Apr 2, 2014
    Posts:
    35
    Thanks I will learn about these subjects:)