无法将类型'UnityEngine.GameObject'隐式转换为'UnityEngine.RaycastHit'

问题描述 投票:-1回答:1

我的脚本中有一些如下代码:

void AttackEntity()
{
    RaycastHit hitInformation;
    var Raycast = Physics.Raycast(Agent.transform.position, Agent.transform.forward, out hitInformation, Range);

// The 'Agent' stuff you are seeing, that is a UnityEngine.AI.NavMeshAgent variable I have created, and 'Range' is a float that (in this case) says how far away an object with the tag "Player" can be to be sensed

    if (hitInformation = GameObject.FindGameObjectWithTag("Player"))
    {

        Agent.transform.LookAt(playerTransform);

// playerTransform is a public Transform that I set up earlier on in the script

    }

}

而且我遇到的错误是在if语句行:

无法将类型'UnityEngine.GameObject'隐式转换为'UnityEngine.RaycastHit'

是否有这样的转换方法?如果是这样,怎么办?或者,也许是FindGameObjectWithTag命令的另一种变体,可用于射线广播。

问候,花岗岩

c# unity3d raycasting gameobject
1个回答
0
投票

RayCastHit不是GameObjectRayCastHit只是一个容器类,其中包含有关射线撞击的信息。您可以访问打过的游戏对象

hitInformation.transform.gameObject = GameObject.FindGameObjectWithTag("Player")

RayCastHit中还有其他信息,请参见this。>>

但是,如果射线没有击中任何东西,则hitInformation将为null,这可能会导致NullRefExceptionPhysics.Raycast返回有关光线是否撞击对撞机的布尔值。您必须检查此值,以避免可能的NullRef

© www.soinside.com 2019 - 2024. All rights reserved.