- Home /
How to access the variables of HingeJoint2d?
Newbie here.
I have an object with a HingeJoint2d attached and I need to access the angle. However, I for some reason I can't. Here is the relevant code:
forceMod = hingeJoint2D.limits.min/51*200;
And the error is:
Assets/Scripts/VelocityScript.cs(15,28): error CS0103: The name `hingeJoint2D' does not exist in the current context
If you need any more information, just say it. Any help is appreciated.
Answer by Kiwasi · Sep 17, 2014 at 07:12 AM
GetComponent<HingeJoint2D>()
I would suggest avoiding the short references and use GetComponent. The other references are being removed from Unity 5 onwards.
The tutorial said GetComponent was expensive in processing power. If I need it every frame, should I still use it?
To make sure the GetComponent won't be necessary every frame, just make a variable and fill it with a single GetComponent in the Start function of your script.
Like so:
private HingeJoint2D mHingeJoint2D;
void Start() {
mHingeJoint2D = GetComponent<HingeJoint2D>();
}
I hope that helps, you can do that for any component. Useful Hint: .transform is a GetComponent in disguise, so try to store that one too if you use it in any updates :3
Thank you, both of you, just one more question though:
Using your example: When you use GetComponent in Start(), and the component changes after that, do you still get the latest version of the component, when you use mHingeJoint2D?
Components are passed by reference. So there is only one copy of the hinge joint. The only time you will run into problems is if you delete the hinge joint and add a new one.
Note that the GameObject.AttatchedComponent syntax is just syntactic sugar, under the hood it does a GetComponent anyway, so you are not saving any processing power.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to access the variables of HingeJoint2d 0 Answers
Sprite Sheet animation without fancy add-ons 1 Answer
if it's you, how will you solve it ? 1 Answer