The title almost asks it all:
GetComponent()
or
GetComponent(typeof(Type))?
I can’t tell on my own.
The title almost asks it all:
GetComponent()
or
GetComponent(typeof(Type))?
I can’t tell on my own.
I can’t imagine the speed is noticeable in any case. Use the former if you want an object of that type returned, or the latter if you want a component.
Wait, I thought GetComponent only returned components?
No, that’s why the Generic version exists!!! :o
//notice you don't need to cast here.
ScriptName sn = gameObject.GetComponent<ScriptName>()
Doesn’t that just mean you get a component attached to an object without having to cast for it?
ScriptName sn = gameObject.GetComponent<ScriptName>();
still returns an object ob type ScriptName, which has to be a component if it’s attached to a GameObject.
Unless I’m missing something entirely, here…
It is a Component, but more specifically, it’s a Behaviour.
It is a Behaviour, but more specifically, it’s a MonoBehaviour.
It is a MonoBehaviour, but more specifically, it’s a ScriptName.
I believe so. I don’t know why you’re thinking about this in terms of attached / GameObject - this is irrelevant. ScriptName sn is an object of type ScriptName, not of type Component, despite the fact that it derives from Component.
Yes you can; run some benchmarks.
float timer = Time.realtimeSinceStartup;
// Do stuff
Debug.Log (Time.realtimeSinceStartup - timer);
(Seems the generic version is about 5-10% slower, i.e. not worth worrying about unless you’re running millions of GetComponent calls in a tight loop.)
–Eric
I guess the lesson here is that GetComponent can return something that’s not specifically a component, even if it probably derives from Component?
Thanks for the answers!
And thanks, Eric, for the benchmarks. I wasn’t seeing the difference.
No, it has to derive from Component, otherwise GetComponent couldn’t get it. The non-generic GetComponent returns a Component. I’d like to see the numbers on GetComponent with a cast, or using “as”, but it sounds really boring so I’ll let someone else post it if they want to. Unless that’s what Eric already did.
I was using a cast. Using “as” seems to be slightly slower, but a bit faster than the generic version. I was using 2.6.1, so the numbers could be different in 3.0. But, like I said, it would have to be an unusual circumstance where the differences actually made any difference. Use whatever’s easiest.
–Eric
Mono was substantially upgraded in 3.0, so for all I know, those numbers are reversed now. Or not. Always run your own tests. ![]()
–Eric