error CS0029: Cannot implicitly convert type in Unity

ConsoleCompiler error · Compiler

error CS0029: Cannot implicitly convert type 'X' to 'Y'

You assigned a value of one type to a variable of another, and C# has no automatic conversion between them. When an explicit conversion exists, such as float to int, the compiler reports CS0266 instead and suggests a cast.

Read the Console line first

X is the type you have, Y is the type the variable needs.

Common causes

  1. GameObject to a component

    A GameObject is not a Rigidbody. Get the component from it with GetComponent.

  2. float to int (CS0266)

    Dividing or multiplying with floats produces a float. Round it with Mathf.RoundToInt, or cast with (int) to drop the fraction.

  3. Between your own types

    Two classes with the same fields are still different types. Map one to the other explicitly.

The fix

Fix
C#
Rigidbody rb = hitObject.GetComponent<Rigidbody>();   // not: Rigidbody rb = hitObject;
int coins = Mathf.RoundToInt(score * 0.1f);           // not: int coins = score * 0.1f;
Vector2 flat = transform.position;                      // Vector3 to Vector2 converts implicitly

Stop it coming back

Read the two type names in the message first: they say exactly what you have and what the variable expects.

Questions

How do I turn a GameObject into a component?
Ask the GameObject for it: Rigidbody rb = enemy.GetComponent<Rigidbody>();. For the Transform, use the shortcut enemy.transform. Going the other way, every component has .gameObject.
How do I turn a float into an int?
Cast it with (int)value, which drops the fraction, or round it with Mathf.RoundToInt(value). Unity also offers Mathf.FloorToInt and Mathf.CeilToInt.
Why does Vector3 to Vector2 work without a cast?
Unity defines implicit conversions between Vector2 and Vector3 (the z value is dropped or set to zero). There is no implicit conversion from a vector to a number; use .x, .magnitude or another member.

Related errors

Got a different error? Paste it into the error lookup.