Assigning position to variable makes my game perform slower;

I created a GameObject that can travel in the main scene. I implemented a code restricting it’s movement so it wont go outside of the boundaries. To make better readability i did:

float posY = transform.position.y;

and so on. But when I started the game whenever character reached the boundaries and would try to move simultanously on x and y axis it would get slowed down significantly because there was some “bumping” happening;

But when I did it likle that:

      if(transform.position.y < -4.38f) {
            transform.position = new Vector3(transform.position.x, -4.38f, 0);
        } else if (transform.position.y > 0) {
            transform.position = new Vector3(transform.position.x, 0, 0);
        }

        if(transform.position.x > 6.25f) {
            transform.position = new Vector3(6.25f, transform.position.y, 0);
        } else if (transform.position.x < -6.25f) {
            transform.position = new Vector3(-6.25f, transform.position.y, 0);
        }

The performance seem to be good, there is no bumping and character is not slowed down when it’s trying to go outside of the boundaries.

So my question is:
Is assigning position (and different things like that, I’m a beginner co can’t think of anything more right now) really affects performance?

Well yes, every thing you do does.

But what you have here should be unnoticeable.

I also thought that, but the difference was huge and I have no idea why.

Assigning performance is not that intesive op, accessing external transform on the native side is.

So if you want to assign position, and modify it a bunch of times, its better to do:

Vector3 pos = transform.position;

if (pos ...){
  pos.x = ....
}

transform.position = pos;

As a bonus, your code will look better.

Caching transform on the managed side is another thing to do if you’re interested in micro-optimizations. Just do it in the OnValidate like so:

[SerializeField]
private Transform _transform = default;
protected virtual void OnValidate() {
    _transform = transform;
}

It’s not neccessary to do, but it can squeese a little bit of op time by removing expensive external fetch call to the native side. (Reference is deserialized by Unity only once instead of accessing external native side each time you do “transform”)

1 Like

Setting position can actually be quite expensive depending on the hierarchy of parent objects, because all those parent transforms have to be accounted for.

You’re always better off using localPosition for anything with a high frequency.

1 Like

Thank you, it definitely helps to learn that at the very beginning :slight_smile: