C# Trouble Setting Variable

So I'm trying to save the object clicked on by the mouse to a seperate variable, but the RaycastHit isn't converting to GameObject, even in an if statement checking its type.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Select : MonoBehaviour
{
    public GameObject selectorPrefab;

    private GameObject selectedObject;
    private GameObject clone;

    void Update()
    {
        if(Input.GetMouseButtonDown(0))//left click
        {
            if(clone)
            {
                Destroy(clone);
            }

            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit) && hit.collider.tag == "Ship")
            {
                Vector3 position = hit.transform.position;
                float scaleMultiplier = (hit.transform.localScale.x + hit.transform.localScale.z) / 2;

                clone = Instantiate(selectorPrefab);
                clone.transform.position = position;
                clone.transform.localScale *= scaleMultiplier;

                if(hit is GameObject)//Green underline here
                {
                    selectedObject = hit;//Red underline under "hit"
                }
            }
        }
    }
}
Jon Skeet
people
quotationmark

Just using the is operator doesn't change the compile-time type of the hit variable. You could either cast within your if body, or use as instead:

var hitGameObject = hit as GameObject
if (hitGameObject != null)
{
    selectedObject = hitGameObject;
}

In C# 7 you could introduce a new variable in the if statement instead:

if (hit is GameObject hitGameObject)
{
    selectedObject = hitGameObject;
}

But if you know that it will always be a GameObject (barring bugs), just cast:

// No if statement, just an unconditional cast
selectedObject = (GameObject) hit;

people

See more on this question at Stackoverflow