- Home /
What am I doing wrong? (converting a javascript code to c#)
I've been banging my head against a wall for about a day now on this one. I'm pretty new to C#, and I don't know any javascript, so there's probably a "duh" answer to this.
I'm going through a Unity tutorial, but the tutorial is using javascript, and I'm learning C#. So far it's been great because the translation has forced me to learn C# instead of just copying the code in the tut.
There are two scripts, one is "scriptPlayer", and the other is "scriptEnemy". In the scriptPlayer script, I'm trying to create a variable "enemyScript" which pulls from scriptEnemy. (I know, I'm probably using all the wrong terminology).
Here's the javascript:
var enemyScript = hit.transform.GetComponent(scriptEnemy);
And here's what I've so far tried to do to convert it to C#:
scriptEnemy enemyScript = hit.transform.GetComponent(scriptEnemy);
But I'm getting errors ('scriptEnemy' is a 'type' but is used like a 'variable').
Any help will be much appreciated!
The tutorial is here, for reference, and he's writing this particular line at 10:40: http://vimeo.com/album/1512103/video/18907342
Answer by robertbu · Jul 25, 2013 at 12:58 AM
scriptEnemy enemyScript = hit.transform.GetComponent< scriptEnemy >();
I love you. Never would have figured that out. Thanks.
Hmm, do you think you could give me a little bit of a "why"? explanation? What do the angled brackets mean as opposed to parentheses?
The syntax is using C# Generics. Here is a link to more than you need to know about Generics:
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
Note there are alternate ways to get a component in C#. Here is another way:
scriptenemy enemyScript = (scriptEnemy) GetComponent(typeof(scriptEnemy));
And here is a link that is very helpful for the syntax differences between C# and Javascript:
http://answers.unity3d.com/questions/12911/what-are-the-syntax-differences-in-c-and-javascrip.html