C#故障设置变量

时间:2017-03-04 00:40:41

标签: c# unity3d

所以我试图将鼠标点击的对象保存到一个单独的变量,但是RaycastHit没有转换为GameObject,即使在检查其类型的if语句中也是如此。

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

2 个答案:

答案 0 :(得分:2)

仅使用is运算符不会更改hit变量的编译时类型。您可以在if正文中投射,也可以使用as

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

在C#7中,您可以在if语句中引入一个新变量:

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

但是如果你知道总是GameObject(禁止错误),那么只需投射:

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

答案 1 :(得分:1)

光线投射RaycastHit的结果不是GameObject;相反,它包含一组有关检测到的匹配的信息,您可以在此处看到:https://docs.unity3d.com/ScriptReference/RaycastHit.html

您正在寻找的对象是hit.collider,它是命中GameObject的一个组件,代表其在物理空间中的音量;您可以使用hit.collider.gameObject检索整个GameObject。