The Unity script reference mentions what looks like a C# generics version of Object.Instantiate(), Object.Instantiate.<> . Is this a typo? Is this a C# syntax I don't know about? In any case, I can't get a generic version to work in my C# script. Is the only option to cast the result into the desired type?
Many thanks!
Argh, threee excellent answers! Which one should I pick, which one should I pick?? Guess I'll go with Jessy's just to even reputations out a bit. :P
You would need a class with extension methods, for that:
using UnityEngine;
public static class ExtensionMethods {
public static T Instantiate <T> (this Object unityObject, T t) where T : Object {
return Object.Instantiate(t) as T;
}
public static T Instantiate<T>(this T unityObject) where T:Object {
return Object.Instantiate(unityObject) as T;
}
}
This is nowhere near as handy as the generic GetComponent, and seems pointless to me, especially given that it will carry overhead. I am interested to know if a generic Instantiate can be faster than using as, if Unity Technologies implements it.
The generic GetComponent also has overhead and looks similar to your implemenetation. In fact, they are calling GetComponent(typeof<T>) as T; (or I can't remember if they used the cast operator. The strange bottom line is that I managed to do an exact similar GetComponent method with less overhead than the built in one. I was quite surprised! However, the price we pay is rather small. A typeof, and a cast.
Yes Jessy, I have replied to another question with more details about it, but I couldn't find it. I'd link it if I had. I tend to mess around with Reflector from time to time to build a better understanding of the engine.
Right. What bothers me is that explicit cast and I thought I could get around it somehow. Oh well, not that big of a deal performance-wise anyway. If the return value ends up being cast anyway, I'd rather have it in my face than hidden behind a sexy function. Thanks everyone!
It's JS syntax, like the generic version of GetComponent. I could never get it to work in either JS or C# though, so I have to wonder if it's actually implemented.
where T was a MonoBehavior. It would create a new game object, create the passed type of MonoBehavior ON that game object, and return a ref to the new MonoBehavior.
My best guess is that they eliminated that function but missed the reference to it in the docs.
Argh, threee excellent answers! Which one should I pick, which one should I pick?? Guess I'll go with Jessy's just to even reputations out a bit. :P
– anon51586091