- Home /
Javascript conversion question
I'm converting the 2d platformer tutorial character controller from javascript to c# and I encountered a problem that I can't find an answer to.
javascript:
// pointer to the player so we can get values from it quickly private var controller : PlatformerController;
function Start () { controller = GetComponent (PlatformerController); }
c# // pointer to the player so we can get values from it quickly private PlatformerController controller;
void Start () { controller = GetComponent (PlatformerController); }
and it gives me the error:
The type or namespace name `PlatformerController' could not be found. Are you missing a using directive or an assembly reference?
any ideas? Thanks.
Answer by Mander · Aug 14, 2012 at 08:45 PM
void Start () { controller = GetComponent<PlatformerController>(); }
That worked. But what does the <> around PlatformerController do?
It's the C# concept of Generics. GetComponent is a generic function, so you have to tell it what type of component it's looking for. In C#, <> indicates that something is being passed as a type, rather than a value or a reference. So what that code really says is "Get Component of type PlatformerController."
The direct translation from JS would have been:
controller = GetComponent(typeof(PlatformerController));
But the generic version using <>
is better because it does a compile-time check. However, the big advantage of the typeof
version over the generic one, is that it also works with interfaces (provided the underlying type does inherits Component
). But this is out of the scope of this question.
Answer by IndieScapeGames · Aug 14, 2012 at 08:41 PM
I think you may need quotes around PlatformController, or, make sure you've properly initialized what PlatformController is.