One common error when using C# is attempting to assign one type of object to another type, and the error can be reported as
- Cannot implicitly convert type ‘Xxxx’ to type ‘Yyyy’
- Cannot convert from ‘Xxxx’ to ‘Yyyy’
- Argument Zzzz: cannot convert from ‘Xxxx’ to ‘Yyyy’
The error means you have an apple, and you’re trying to put it in the orange slot, or some other inappropriate assignment.
Like “Null Reference” and “Index Out Of Bounds” exceptions, the “Cannot Convert” family of exceptions are extremely common and generally simple-to-fix errors, but you need to understand what you are doing.
Fortunately the compiler gives you a great start and tells you exactly which line the error is on, so double-click that error in the console and go look at your code.
Sometimes you can add something to facilitate making what you want to happen, and this is called casting.
But far more often you simply are trying something that can’t be done, for instance assigning a float into a Vector3. A Vector3 is three (3) separate floats named x, y, z, so in that case you can only assign your float into one of those floats.
To reason about what you are doing, you need to understand two things:
- What are you assigning (the part to the right of the equal sign)
- What are you assigning it to (the part to the left of the equal sign)
Stop and ask yourself, what type of object is on the right? Is that a float? Is it a GameObject? An int? A Vector3? A Quaternion? Figure that out first. Don’t go any further.
You absolutely must understand what you are trying to assign in order to actually function as a software engineer. It’s not optional so start now.
Then go to the left side and say “Where I am putting this, what is this item?” If it isn’t the exact same type of object, it probably won’t work.
Now you have some clues to begin investigating what you are trying to accomplish. Start with asking yourself, “What is the purpose of this line of code?” If you can articulate clearly what you’re trying to do, that implies you know the source and the destination data types.
And finally if you get stuck, start googling the error. That’s almost always going to give you some insight.