liveBook · Manning

Value type

As explained in High Performance Unity Game Development

A data type whose values are copied directly when passed or assigned, rather than passing a reference to the same object.

A value type stores its value directly. When passed to a function, that value is copied, so changes to the copy do not change the original. Structs and primitive types are value types; classes, arrays, and strings are reference types, whose references are copied instead. section 2.3

When choosing a representation for game data:

  • Prefer a small struct for temporary data made of primitive values that are used together. Treat 16 bytes as a guideline, not a hard limit. section 2.7 section 2.1
  • Keep structs small because passing them copies their contents; use the ref keyword when you need to pass a struct by reference and avoid that copy. section 2.7
  • Test performance on the target device: struct-passing behavior can differ between the Unity Editor, Mono, and IL2CPP. section 2.1 section 2.7

Position data and enemy data

A Vector2 position is an 8-byte struct containing two floats that are used together. By contrast, EnemyData groups arrays for position, direction, and velocity; that data is variable-sized and not always used together, making a class a better fit. section 2.1

Listing 2.1 C# class holding all the data for all enemies
public class EnemyData
{
    public Vector2[] Position;
    public Vector2[] Direction;
    public float[] Velocity;
}

The EnemyData listing shows arrays grouped in a class, illustrating a case that does not fit the small-struct criteria. section 2.1

How High Performance Unity Game Development covers it

How deep it goes
Explains copying semantics and performance caveats, treating 16 bytes as a guideline rather than a hard limit.
Examples
Uses Vector2 position data and an EnemyData class containing arrays to contrast representation choices.
What you can do after
Evaluate whether temporary, tightly coupled primitive data fits a small struct, and use ref when avoiding a copy is warranted.
How it connects
Connects value types to structs, reference types, classes, stack and heap memory, and argument passing.

Also explained in

Compare how 3 books explain value type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of High Performance Unity Game Development. The section links point to the parts of the book it draws on.