Skip to main content

avoid-creating-vector-in-update

added in: 1.0.0 warning.

Warns when a Vector2 is created inside a Component's update method.

Creating a new vector every tick can affect the performance. Instead, an existing vector should be updated.

Example

Bad:

class MyComponent extends Component {
@override
void update(double dt) {
final newVector = Vector2(10, 10); // LINT
}
}

class MyComponent extends Component {
final vector1 = Vector2(10, 10);
final vector2 = Vector2(20, 20);

@override
void update(double dt) {
final addVector = vector1 + vector2; // LINT
final subVector = vector1 - vector2; // LINT
}
}

Good:

class MyComponent extends Component {
final _temporaryVector = Vector2.zero();

@override
void update(double dt) {
_temporaryVector.setValues(10, 10);
}
}

class MyComponent extends Component {
final vector1 = Vector2(10, 10);
final vector2 = Vector2(20, 20);

final _temporaryVector = Vector2.zero();

@override
void update(double dt) {
_temporaryVector
..setFrom(vector1)
..add(vector2);
}
}