- Home /
Can't understand generic getComponent for Js
What's the deal? I looked over the other posts regarding the generic versions of getcomps but I still don't understand exactly how to use it. I'm using js.
I am curious because I read somewhere that generic is better for performance? If so, how so?
I am practicing with this but I keep getting errors
var script : behaviorScript;
script = GetComponent.<behaviorScript>();
headBone = script.headBn;
Error: behaviorScript is inaccessible due to its protection level.
what's wrong with it?
My goal is to not have to type out 'GetComponent' every time I need something from another script. I would like to be able to just say 'script.Blah()
'. I use getcomponent quite a bit and in update, so if I save on performance I really want to learn this.
Thanks
Ps Does
var script : someScript;
actually detect any script named someScript that is attached to this game object? Even if the script asking for it is a child of the intial gameobject?
Generics are typically more efficient than types since they often avoid the need to use reflection. Whether or not generics are more efficient for the GetComponent
function is a different question since we do not know how GetComponent
is implemented. I shouldn't think that there would be a noticeable difference in this case.
Though, the generic version of AddComponent
is likely to outperform the non-generic version since it will almost certainly avoid the use of reflection. But again, this depends upon how it is implemented.
I would recommend to use the generic version for consistency throughout your scripts.
A little tip with regards to your na$$anonymous$$g of classes and other types. I would recommend using ClassNameLikeThis
ins$$anonymous$$d of classNameLikeThis
because this will help to make your code more readable by avoiding confusion with variables and fields.
Answer by superventure · May 26, 2013 at 06:49 AM
I found out what the problem was- I had the variable I wanted to access marked as private. When I declared it public, it worked. I would still like to know if this method is better for the engine, if someone could please explain?
Your answer
Follow this Question
Related Questions
Help with accessing scoring system variable C# plz. 3 Answers
Accessing other gameobject's script variables : why doesn't this work? 2 Answers
Changing variables in another script 3 Answers
How to set a variable equal to another variable in another gameobject? 2 Answers
Why can't I change another script's variable with this script? Thanks, 1 Answer