Physics2D.Raycast 返回 null [英] Physics2D.Raycast returning null

查看:40
本文介绍了Physics2D.Raycast 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个让我非常困惑的问题.我将从关键代码到鼠标输入 - 然后它后来成为触摸输入,但首先我想弄清楚为什么我不能只用鼠标来做到这一点.

I have a bit of a issue that has me super stumped here. I am going from Key codes , to mouse input - then it later become touch input, but first I want to figure out why i cant do this with just a mouse.

我有一个 raycast2d 设置 - 我希望 raycast 读取与屏幕上我的对象的碰撞.只有当它是一个标记为猫"的物体时,它们才会做出反应——基本上一旦发生这种情况,猫就会冲出去并试图攻击.但是,它告诉我标签本身是一个实例化的引用.但是对象本身默认存在,所以我不确定在这里做什么.这是我的整个脚本.

I have a raycast2d setup - and I want the raycast to read collision with my objects on the screen. They are to only react if its an object tagged as "Cat" - essentially once that happens, the cat will swipe out and try to attack. However, it tells me the tagg itself is a reference that instantiated. But the object itself exists by default so im not sure what to do here. Here is my whole script.

 void Update() {
    //if ((Input.GetKeyDown(KeyCode.O) && !attacking && attackTimer <= 0)) {
    if (Input.GetMouseButtonDown(0) && !attacking && attackTimer <= 0) {  //every frame check to see if the mouse has been clicked.
                                                                          //Get the mouse position on the screen and send a raycast into the game world from that position.
        Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);//Vector 2 means only 2 points of axis are read. worldpoint means check the point of the world. Camera is used to determien what we are looking at, and we fill it with our mouse location.
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
        if (hit.collider == null) {//THIS IS THE LINE that says it is having issues. If i REMOVE this line, ANYWHERE i click on the screen activates the cat and thats not what I want to happen.

            Debug.Log("No Object Touched");

            if (hit.collider.CompareTag("Cat")) {
                GameManager.Instance.AudioSource.PlayOneShot(SoundManager.Instance.Swipe);

                attacking = true;
                attackTimer = attackCd;

                attackTrigger.enabled = true;
            }

更新代码以匹配请求的更改:我现在得到的错误是 NullreferenceException - 对于:

UPDATED CODE TO MATCH REQUESTED CHANGES: The error im now getting is the NullreferenceException - for:

 if (hit.collider.CompareTag("Cat")) {

这与我之前遇到的错误相同,在使用程序员推荐的方法重新测试后.

This was the same error i was getting before, after retesting with the methods programmer recommended to test.

控制台会显示我没有点击对象,然后显示空值.所以我想它试图告诉我它没有找到任何存在于场景中的标记为 cat 的东西?尽管 Cat 是添加的自定义标签,并且它已应用于作为猫的游戏对象 - 带有 Box 碰撞器.它是否需要材料或任何东西来阅读它是否存在?有没有另一种方法可以通过点击它的特定位置来调用这个对象?

The console WILL show me, that I have not clicked a object, then show me the null. So I guess its trying to tell me that it doesnt find anythign tagged as cat that exist in the scene? Even though Cat is a custom tag added, and it was applied to the game object that is the cat - with a Box collider. Does it need a material or anything to read it exists? Is there another way I can call this object on click of its specific location?

更新:

       Debug.Log("No Object Touched");
                if (hit.collider) {
                    if (hit.collider.tag == "cat1") { - 

这摆脱了空引用,但它根本不读取猫.如果我点击猫没有任何反应.是的,它现在在编辑器中正确标记为cat1".meanign 标签 - 新的自定义标签,创建了 cat1 标签.转到游戏对象,将标签更改为 cat1.还确保一个 colider 是打开的,并且是触发器.

this got rid of the null reference, BUT It doesnt read the cat at all. if i click the cat nothing happens. and yes it is now tagged as "cat1" properly in editor. meanign tags - new custom tag, created cat1 tag. went to game object, changed tag to cat1. Also ensured a colider is on, with is trigger.

推荐答案

经过几个小时的搜索,我终于找到了为空的原因.

After hours of searching, I finally figured out the reason for getting null.

您需要将New Component">Physics">Box Collider"附加到您的精灵游戏对象.

You need to attach 'New Component' > 'Physics' > 'Box Collider' to your sprite game object.

现在您可以在添加到游戏对象的脚本中使用以下代码片段来了解对象是否被点击:

Now you can use the below code snippet in the script added to your game-object to know if the object is clicked:

private Ray ray;
private RaycastHit hit;

private void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) 
    {
        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            if (hit.transform.gameObject.name == "YourGameObject")
            {
                // Do your stuff on click
            }
        }
    }
}

这就是为什么 3d 对象可以轻松检测到触摸的原因,因为在您创建它们时,它们已经附加了对撞机.

This is the reason why 3d objects can easily detect touches, because they already have colliders attached to them when you create them.

希望这个答案对某人有所帮助.

Hope this answer helps someone.

这篇关于Physics2D.Raycast 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆