GetComponent C# syntax.

Can you please point out the GetComponent syntax for C# because I dont seem to get it working. I am finding the gameoject I want with
GameObject foo = GameObject.Find().
Then I am using
foo1 = foo.GetComponent(MyScript)
an I get "The name MyScript does not exist in the current context. I am certain I am using the wrong syntax here so please any suggestion will be helpful.

Maybe you should write MyScript as a string: “MyScript”

foo1 = foo.GetComponent(“MyScript”)

MyScript foo1 = foo.GetComponent(typeof(MyScript)) as MyScript;

Or:

MyScript foo1 = (MyScript) foo.GetComponent(typeof(MyScript));

The difference is that using “as” would return null if there is an object but it cannot be casted to the given type (which can never happen with this because you’ve asked for a specific type). Using the “usual typecast” (“(TypeToCastTo) expressionReturningObject”), you’d get an InvalidCastException if GetComponent(…) returned an unexpected type (“which can never happen …”).

See also C# Programmer’s Reference / Operator Keywords / as

Hm … preview tells me: This forum doesn’t really like Microsoft’s links with parenthesis :wink:

Anyways … this reference also says:

… which, to be honest, I don’t really understand (what are “user-defined conversions”?) :wink:

It doesnt seem to work. Hmmm, I dont get it. i am using what you suggested but this time it says “The type or namespace MyScript could not be found. Are you sure you are not missing a using directive or assembly.”
I thought Unity would take care of the script finding automatically.

Um … you can’t use “MyScript” (unless you named your script “MyScript” which would be a rather bad choice for a name) - you need to use the name of your MonoBehaviour (the classname). Unity can’t know which of the attached components (scripts, whatever) you’re looking for unless you tell it which one you want.

I am trying to find a javascript attached in another component. Can you show me an example. Thank you for all the help.

Oh, you’re trying to call JavaScript from C#. That’s a little more involved due to compilation order. You need to make sure that the JavaScript files are compiled before the C# files. Otherwise, it won’t work.

I think that’s explained somewhere in the documentation, and this has also been discussed on these forums before. IIRC, you need to put the C# for example into the Editor folder (I think Editor scripts are compiled after the rest, but it might also be the other way round, not sure - then you’d have to put the JavaScript stuff into the Editor folder). Either Editor folder or Plugins folder (I think).

But in general, I’d recommend not mixing C# and JavaScript. It’s possible, but it will give you more pain than you want …

Required reading for mixing JavaScript/C#/Boo

Ok I figured it out about script compilation order. Hmmm, tricky at first. Thank you.