- Home /
if statement or just setting transform.position?
(I feel like somewhere this question must have been asked, I just can't seem to find the answer, so if someone can redirect me to the answer I'll gladly delete the question.)
I have this code in a little gizmo I'm making, inside the update function:
if (transform.position.x != transform.parent.position.x)
{
transform.position.x = transform.parent.position.x;
}
Is there any point in the if statement here? Does checking if the positions are the same actually have a performance hit the same as just assigning the position every frame?
Thanks!
Could you have a little bit more about the parent and child, it would help clarify the answer.
Checking before assigning looks cleaner and I think it is more performance friendly.
You could use an event that doesn't require you to actively check for the parent's location.
Or you could have the parent move the child when it moves.
In both cases, Child will move Only when parent moves. And you won't have to keep track of it.
maybe the logic is to not use extra memory everytime when setting postition of parent to child ....
Basically I'm just locking the child's x position to the parents x position. It's more a general question about whether using the if statement each frame is just as much of a performance hit as just setting the transform. I'm not looking for alternative methods. Thanks :)
Answer by robertbu · Sep 03, 2014 at 05:23 PM
There's no point in checking. Beyond that, accessing a game object's transform has a hidden GetComponent() call. So, in addition to accessing the variable twice, you are also calling GetComponent() twice. The usual way around the GetComponent() call is to get it once in Start(), and then use your class instance variable.
That's great thank you. I normally would cache the transform but I'm just being lazy while I write the script :D Thankyouverymuch!
Your answer
Follow this Question
Related Questions
How do I make my script switch back to my regular animations 1 Answer
JavaScript issue: apparently invisible variables 1 Answer
Road Texture Is Stretching 3 Answers
Camera Move 1 Answer
How do I reset a variable? 2 Answers