- Home /
UnityScript - Class reference
My question is how do I use a link/reference/reflection for my class?
Here goes my ActionScript code that I want to realize in UnityScript. Let's assume I have a public class named "MyClass" and I want to give it as a parameter to my function.
function CreateObject(user_class: Class): Object {
var o = new user_class();
return o;
}
...
var my_obj = CreateObject(MyClass);
How can I make it in UnityScript?
PS: Of course, I don't need such simple function. But it shows an idea.
I could show you how to do that in C#. Do you want me to? Unfortunately, I'm not too familiar with Unity's weird Javascript implementation...
Ok, I just wrote an answer for this, and I realised that there is very little practical difference between this and just using a plain constructor. Why can't you just do that?
I know how to do that in C#, Java and ActionScript. But now I wounder how to do that in JS/UnityScript. The idea was not just about creating an instance. The idea was to make some classes (inherited from the base interface) with the fixed set of methods. And to make a class that can work with any of these classes.
As I've said in the comment below, the first idea was to create an instance of my class and to use an instance as a parameter, but that seems to be a bit not right for me - when you're creating an instance just to use its (static) methods, without any need of instance itself.
Answer by syclamoth · Apr 17, 2012 at 11:59 PM
Well, if you want it, here's some C# code:
public T CreateObject<T>()
{
return new T();
}
var my_obj = CreateObject<MyClass>();
Of course, why can't you just use
MyClass my_obj = new MyClass();
?
The only functions you would have available in 'CreateObject' would be ones that are common to all object types- pretty much just ToString, GetHash, and a few other things. If you wanted to use this for something useful, I would recommend creating an interface that defines the commonly-used functions for those classes that you would like to use in this way. Then, limit the function so that it only accepts classes that implement that interface.
$$anonymous$$y code above is just an illustration. Of couse, the real code is $$anonymous$$UCH more complex then just creating an instance.
Ok, your code on C# is good, but that doesn't help me - I need to implement something like this in UnityScript ;)
About the 2nd part of your answer - yeah, that was my first idea! But that's looks like a little not-right. Creating an instance of a class just to call some methods - that is not what the objects in OOP are for :) So, I thought if there is another (more OOP-correct) way to do something like that.