Skip to content

Optimization: GetComponent #1

Description

@nick-bors

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions