Search Unity

GetComponent in c# script

Discussion in 'Scripting' started by helmishariff, Dec 7, 2007.

  1. helmishariff

    helmishariff

    Joined:
    Nov 29, 2007
    Posts:
    107
    Hi, it's working when I use this script using javascript but not in c#
    //javascript
    var someScript : ExampleScript = GetComponent (ExampleScript);
    someScript.DoSomething ();

    //c#
    ExampleScript someScript;
    someScript = GetComponent (ExampleScript); //error here.
    someScript.DoSomething ();
     
  2. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    try this:

    Code (csharp):
    1. someScript = GetComponent (typeof (ExampleScript));
     
  3. Jonathan Czeck

    Jonathan Czeck

    Joined:
    Mar 17, 2005
    Posts:
    1,713
    Code (csharp):
    1. Type variableName = objectName.GetComponent(typeof(Type)) as Type;
    Cheers,
    -Jon
     
  4. helmishariff

    helmishariff

    Joined:
    Nov 29, 2007
    Posts:
    107

    Hey! thanks.. it's working.. :)
     
  5. jashan

    jashan

    Joined:
    Mar 9, 2007
    Posts:
    3,307
    Or

    Code (csharp):
    1. Type variableName = (Type) objectName.GetComponent(typeof(Type));
    Which has the advantage, that it doesn't immediatly create a NullReferenceException during runtime, when the component does not exist and therefore GetComponent returns null.

    You could then do a check

    Code (csharp):
    1. if (variableName != null) { ... }
    to avoid trouble when accessing variableName... another option, of course, is using GetComponent(...) as Type embedded in some try { ... } catch (NullReferenceException exc) { ... }...