How to fix “Cannot implicitly convert type” C# errors

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.

How to break down “hairy code” that has an error.

Frequently you will encounter an error in a piece of code such as this:

GameObject.FindWithTag("Player").GetComponent<CharacterStats>().AddToStrength(5);  //null ref error here, I needz helpz!!!

With the above code and most IDEs, there is no easy way to reason about what has failed. This means you must rewrite the code to further expose where the error might be.

For instance, the above code could be re-expressed as follows:

// original from above:
//

GameObject.FindWithTag("Player").GetComponent<CharacterStat>().AddToStrength(5); //null ref error here, I needz helpz!!!

// rewrite the above as:
//

GameObject playerObject = GameObject.FindWithTag("Player");
if (playerObject == null)
{
Debug.Log("FindWithTag returned null for Player tag");
}
CharacterStats stats = playerObject.GetComponent<CharacterStats>();
if (stats == null)
{
Debug.Log("playerObject.GetComponent returned null");
}
stats.AddToStrength(5);

Now you can re-run your game and see precisely which statement above is failing, and thus have a chance to fix it.

Hat tip to @Joe-Censored on the Unity3D forums for the above code.

How to fix Index Out Of Range errors in Unity3D

A very common problem in Unity programming is the Index Out Of Bounds Exception

A related cousin is the Argument Out Of Range Exception.

Both mean the same thing. One is for arrays, one is for other types of collections.

What it means is you have a collection of items, but you’re asking for something outside of that collection.

For instance if you have three things, you are asking for the fourth (or greater) one.

Keep in mind that if you have three things, they will be indexed by 0, 1, 2.

If you ask for thing at index 3, that is the fourth thing and it is out of range of a three-thing collection.

Similarly, if you ask for thing -1 (minus one), that also cannot happen.

Another tricky part of this one is that often when you doubleclick on the error, Unity does not take you to the offending line of code, or else it takes you to the wrong line of code.

However, you can still get there manually by looking at the error text itself.

Select the error in the console window and then look down in the lower panel of the console window. Find the first line that is your script, and that will contain a number that tells you where the error is. In some newer versions of Unity you can even click in that window to be taken there.

If after all that you are baffled by why you are getting this error, and you are POSITIVE that there are enough items in your collection to satisfy your dereference operation, then you need to put a Debug.Log() call right before the point where you get the error, and print out two things: the index you are dereferencing, and the Count (or Length) of the collection itself.

Now you have some information to go track down why in fact you do not have enough items in the array.

How to report a problem in the Unity3D forums

Many people struggle with properly reporting a problem on the Unity3D forums. This post is to try and help you get it right and speed up your return to success.

Step 1. Choose a good subject line. Don’t choose “Help!” or “Doesn’t work” Instead say “Need help with inventory system” or “Getting an X error when I pick up an item.”

Step 2. Do a little bit of basic research on your own. Double-click the actual error and try to see what code it relates to. Google the error text itself. Read at least two or three results. You will NEVER be the first person to have this error, trust me.

Step 3. Identify at least the ballpark area where the error is in your code. Extract the relevant section of code, as little as you think will show the problem, and post it here. If you don’t post code, we can’t help you. If you post massive amounts of code, we’ll assume you’re not even trying to be helpful. If nothing is happening, use Debug.Log() to find out if your code is even running.

Step 4. When you post code, use CODE tags (in square brackets) to format your code so we can read it. Do not retype your code; use copy / paste-match-style, otherwise you’ll introduce extra typos.

Step 5. Tell us the following things and be very precise:

1. What you think it should be doing

2. What it actually is doing

3. What things you have tried in order to fix it

4. Any other interesting tidbits you think might be relevant

Keep in mind the point of the Unity forum is not for us to write your script for you. It’s for YOU to write your script, and when you get into trouble, come ask questions in the forums, paying attention to the notes above.

Also if you are following a tutorial, none of us here are going to go and try out the tutorial to see where you have the problem. It falls on you to first understand it well enough to present your issue in terms of the above requirements, otherwise we simply are not going to be able to help you.

How to find a nullref in Unity3D scripting

I am developing a standard “How to handle a nullref” post, since it is the most-common and (usually) simplest form of error encountered when scripting in Unity3D. It is also an error you will see forever into the future as long as you do software engineering. Get really familiar with fixing it.

Steps to find a Null Reference (nullref) error:

In the console, double-click the error to figure out where it is in your code. The error text shows the file name, the line and possibly the character. The lower part of the console may also have the stack trace leading here.

What is in that line of code that could be null? (reference types obviously)

Is it a complicated hairy line of code? Then break it down into constituent statements, run it again, find where the error is now.

See http://plbm.com/?p=248 for tips on breaking down hairy code.

When you know which variable is null, now ask yourself:

  • what mechanism is supposed to set that variable up? (UnityEditor? GetComponent? GameObject.Find()? Something else?)
  • why is it not being set up? (Unable to find? Misconfigured? Code not being called? Setup code called later than access code? Something else?)
  • fix it.

You can do this. Trust me.

ALSO: often the very first nullref begets 999+ more. ALWAYS start with the very first one at the very top of your log, because often it will trigger all the others, which aren’t really an actual problem.

Tank Dynamaze has arrived for Android TV!

You can play Tank Dynamaze on your Android TV! Get it here:

https://play.google.com/store/apps/details?id=com.plbm.dynamaze2dtv

Use either a single DPAD controller or a dual-analog setup to drive your tank through an ever-changing dark maze, looking for the elusive master enemy bunkers to destroy.

Mix it up with enemy helicopters, enemy tanks and enemy bunkers and blast your way to the best global score!

Demo Night Tonight (Meetup)

I’ll be demoing tonight at the Orange County Unity3D Meetup. Details here:

Demo night/lightning rounds and holiday gathering (Unity & IGDA)

Tuesday, Dec 18, 2018, 6:30 PM

Mobilityware
440 Exchange #100 Irvine, CA

61 Developers Attending

Happy Holidays! This next event we’re going to have a walk-around networking & demo night and some lightning rounds. Lightning rounds are five minute quick demos. We’re joining our two groups (OC Unity and IGDA OC) together for this meetup. Bring whatever you want to demo that you are working on. Be it a game, VR Experience, tool, art work, or som…

Check out this Meetup →

You can get all my games here: