Is there performance penalty to setting a transform property value (e.g. localScale) to the current value?

  • I'm using the code above to 'mirror' the 2D player character based on a keypress or more precisely the direction in which it moves. Is it bad practice or do I suffer some performance penalty if I set transform.localScale to a value that it currently has? If the player character keeps moving right the localState value will constantly stay the same.


    I would hope that setting the values is separate from the rendering itself but I want to be sure that my solution is an acceptable one. Is there a better way to do this kind of thing? Does Unity have such a feature out of the box?

  • Thank you for your reply. I was hoping Unity was smart enough not to trigger any computation if the values are the same :) but I can handle this manually, not a problem.


    I would like to follow up with a more general question about performance and the Update method. This is what I'm doing there now:


    Code
    1. // Update is called once per frame
    2. void Update()
    3. {
    4. Vector2Int currentTile = tileManager.GetGridPositionForCoordinates(this.transform.position);
    5. SpawnBomb(currentTile);
    6. CheckGhostMode();
    7. CheckManualTrigger();
    8. CalculateMovement(currentTile);
    9. }

    The snippet I posted originally is part of the CalculateMovement method:

    What I'm writing is a Bomberman clone and it's tile-based so once the character starts moving in one direction it doesn't stop until it reaches the target tile. There is no physics involved, the interaction with objects is done using colliders and the movement is done with transform manipulation. Could you tell me if the way I put those methods in the Update method is good enough? Should I use LateUpdate or FixedUpdate for some of those?

  • I've noticed that the .Flip sometimes doesn't do what you might want it to do.
    At those times I've done something like this.


    Code
    1. void Flip()
    2. {
    3. // Switch the way the player is labelled as facing
    4. facingRight = !facingRight;
    5. // Multiply the player's x local scale by -1
    6. Vector3 theScale = transform.localScale;
    7. theScale.x *= -1;
    8. transform.localScale = theScale;
  • I've noticed that the .Flip sometimes doesn't do what you might want it to do.
    At those times I've done something like this.


    Code
    1. void Flip()
    2. {
    3. // Switch the way the player is labelled as facing
    4. facingRight = !facingRight;
    5. // Multiply the player's x local scale by -1
    6. Vector3 theScale = transform.localScale;
    7. theScale.x *= -1;
    8. transform.localScale = theScale;

    Yeah, if I go for a flip method I will just *-1 the x part of the scale. The way I do it know I have to constantly set the proper value. Thanks.