Trouble Converting RaycastHit to GameObject

So I’m trying to save the object clicked on (RaycastHIt) by the mouse to a seperate variable, but the RaycastHit isn’t converting to GameObject, even in an if statement checking its type. Please help, and thanks in advanced!

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"
                }
            }
        }
    }
}

Please help guys.

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;

                selectedObject = hit.transform.gameObject;
            }

I would get rid of the if(hit is GameObject)
you are already checking if the tag = “Ship”. so you should be clicking the correct object.

to fix the red line error
selectedObject = hit.transform.gameObject;

1 Like