Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Get Component for variable in C#

Discussion in 'Scripting' started by TJB, Jul 4, 2009.

  1. TJB

    TJB

    Joined:
    Mar 20, 2007
    Posts:
    146
    Hi,
    I'm trying to get access to variables from another script in C#

    in javascript i'd use:
    variable = GameObject.Find("myobject").GetComponent("myscript").othervariable;

    but this doesn't seem to work. In c# it says:
    UnityEngine.Component does not contain a definition for othervariable

    Thanks for any help you can provide
     
  2. lankoski

    lankoski

    Joined:
    Apr 20, 2008
    Posts:
    148
    Try (untested, but you should get the idea):
    Code (csharp):
    1. variable = (GameObject.Find("myobject").GetComponent(typeof(myscript)) as myscript).othervariable;
    GetComponent returns object of type Component. Because of that you get it in correct type. You could also cast it:

    Code (csharp):
    1. variable = ((myscrip)GameObject.Find("myobject").GetComponent(typeof(myscript))).othervariable;
    I would not use string version of GetComponent as it is slower than alternative one. In addition, with typeof() compiling fails if there is something wrong (e.g., typo in class name).
     
  3. pengyj1984

    pengyj1984

    Joined:
    Jun 21, 2009
    Posts:
    58
    If myscript is javascript. You must put it in precompile step. Otherwise you can't access it in c# script.
     
  4. JohannChristoph

    JohannChristoph

    Joined:
    Jun 21, 2009
    Posts:
    141
    oh, this sounds interesting. I thought it is not possible at all to share one and the same Variables across JavaScript and C# scripts.
    Can you briefly describe what you mean by put it in precompile step? Is that difficult. (I am very new to programming)
     
  5. pengyj1984

    pengyj1984

    Joined:
    Jun 21, 2009
    Posts:
    58

    You can see this link:
    http://unity3d.com/support/documentation/ScriptReference/index.Script_compilation_28Advanced29.html
     
  6. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    You can't share them.
    You can only expose them from JS to C# or from C# to JS, but knowledge of the other class will never work in both directions.