Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

problem with type casting between scripts

Discussion in 'Scripting' started by qgi, Aug 17, 2007.

  1. qgi

    qgi

    Joined:
    Feb 12, 2007
    Posts:
    8
    Hi there.

    For very simple multi-language support in my project, I've added a function to the GameController script (JS) that returns a String depending on the language. But every time I try to assign that returned String to a GUIText (or even to a String variable I get a type cast error.). I'm new to JavaScript.

    Here's the sample code for GameController.js
    Code (csharp):
    1.  
    2. function Hello()
    3. {
    4.     return "hello";
    5. }
    6.  
    Code from the actual script attached to another GameObject
    Code (csharp):
    1.  
    2. var x : String = GameObject.Find("GameController").GetComponent("GameController").Hello();
    3.  
    Even that gives me an "InvalidCastException: Cannot cast from source to destination type."

    Thanks in advance,

    qgi
     
  2. HonorableDaniel

    HonorableDaniel

    Joined:
    Feb 28, 2007
    Posts:
    2,970
    Try this

    Code (csharp):
    1. var hello = Hello();
    2.  
    3. function Hello()
    4. {
    5.    return "hello";
    6. }
    Code (csharp):
    1. var x : String = GameObject.Find("GameController").GetComponent ("GameController").hello;
    I'm not sure why yours doesn't work.
     
  3. qgi

    qgi

    Joined:
    Feb 12, 2007
    Posts:
    8
    Daniel,

    Thanks for the help! That really does the trick for that bit of code.

    But what do I do if I need to pass a parameter?
    What I really want to do is something like calling Hello(language:int) that returns a String in a language (I use a "dictionary" Array that returns a String based on the given language).


    I also tried to declare my function as
    Code (csharp):
    1.  
    2. function Hello() : String
    3. {
    4.      return "Hello";
    5. }
    6.  
    but this didn't do it either (same exception, no complains about the ": String" bit though)

    Thanks again!
    qgi
     
  4. hai_ok

    hai_ok

    Joined:
    Jun 20, 2007
    Posts:
    193
    I'm working with the same things here and would love some further insight.
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,254
    I just tried:

    Code (csharp):
    1. var x = GameObject.Find("GameController").GetComponent("Test").Hello(1);
    2. print (x);
    with "Test" being:

    Code (csharp):
    1. function Hello (which : int) {
    2.     if (which == 1) {return "Hello";}
    3.     else {return "Hola";}
    4. }
    and it works fine. That method uses dynamic typing, even if you specify "var x : String", so make sure you're not using "#pragma strict";

    --Eric
     
unityunity