How to account for a failed raycast?

So in my game, a user throws a gem onto a board, and it’s supposed to match with other gems that are already on the board – similar to bejeweled. When the gems match, they delete, and I have a series of raycasts look for gems above/below (depending on whose turn it is) to replace the deleted gems.

The problem is that if there’s no gem for the raycast to hit, the script just stops execution and returns the error:

“NullReferenceException: Object reference not set to an instance of an object
CamDragDetector+$ReplaceGems$65+$.MoveNext () (at Assets/Scripts/CamDragDetector.js:227)”

Example can be seen here: http://imgur.com/a/HdPWK

So, is there a way I could account for the lack of a gem to hit? My raycast outputs to hit3, so I tried using something like “if(!hit3.tranform)”, but that doesn’t seem to work.

Code:

// gemsList is the list of matching gems
for (var c = 0; c < gemsList.Count; c++) {		
	// Set up some variables...
	var origPos = gemsList
.position;
    	var nextPos : Vector3;
    	var hit3 : RaycastHit;
    	
    	// Destroy a matching gem
    	Destroy(gemsList[c].gameObject);
    	
    	// Now we need to shift all relevant gems in a direction
    	do {
    		// Change raycasts based on whose turn it is
    		if (turnInt == 1) {
    			raycast = Physics.Raycast(origPos, origPos.up, hit3); }
    		else if (turnInt == 2) {
    			raycast = Physics.Raycast(origPos, origPos.down, hit3); }
    		
    		if (raycast) {
    			// The gems that move have to be tagged "BoardGem"
    			if (hit3.transform.tag == "BoardGem") {
    				nextPos = hit3.transform.position;
    				hit3.transform.position = origPos;
    				origPos = nextPos;
    			}
    				
    			// This stores the position of the last BoardGem, for CreateGems() to initialize at that position
    			missingPos.Clear();
    			missingPos.Add(origPos);
    		}
    	}
    	while (hit3.transform.tag == "BoardGem"); // This line is where the error hits
    	
    	// Create new gems as replacements
    	CreateGems();
    }

Thanks in advance!

I guess you try to call hit3.transform, but hit3 is null.

So your condition should be

if (!hit3 || !hit3.tranform) {...}