Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimization: GetComponent #1

Open
fami-fish opened this issue Dec 1, 2022 · 0 comments
Open

Optimization: GetComponent #1

fami-fish opened this issue Dec 1, 2022 · 0 comments

Comments

@fami-fish
Copy link

fami-fish commented Dec 1, 2022

GetComponent

Unity's GetComponent() function is very expensive. You should cache the Rigidbody as such:

private Rigidbody rb;
private void Start() {
    rb = GetComponent<Rigidbody>();
}

Ideally you would not want to run GetComponent every frame in Update; especially multiple in times. This will (probably) increase fps (since unity does not need to look it up multiple times before the next frame) and cpu load.

Re-Assignment

The code snippet below includes two IF checks; two assignments and two re-assignments

onGround = CheckGround();

//Different acceleration values for ground and air
float curAccel = accel;
if (!onGround)
    curAccel = airAccel;

//Ground speed
float curMaxSpeed = maxSpeed;

//Air speed
if (!onGround)
    curMaxSpeed = maxAirSpeed;

It could be refactored to include only two IF checks and two assignments (and its concise)

onGround = CheckGround();
float curAccel = onGround ? accel : airAccel;
float curMaxSpeed = onGround ? maxSpeed : maxAirSpeed;

These are just a few suggestions to make your game more accessible to those on lower spec hardware :)
Remember, optimization is easier to do when you write code rather than refactor it later on

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant