【问题标题】:Projectile is detecting both the wall and the "grunt" as a "grunt"Projectile 将墙壁和“咕噜声”都检测为“咕噜声”
【发布时间】:2020-03-11 20:51:50
【问题描述】:

我有一个从玩家发射的射弹预制件,当它与“边界”碰撞时,它应该会自行摧毁,而当它击中“咕噜声”时,它应该会摧毁自己和咕噜声。然而,当它撞到边界时,它会破坏自身和边界的对撞机。我创建了一个自定义标签脚本,允许我将多个标签分配给一个游戏对象,而不仅仅是一个。

为什么它会破坏墙壁对撞机? 为什么它将墙壁和咕噜声都检测为咕噜声? 我将如何解决它?

这是导致问题的脚本:

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

public class MyProjectile : MonoBehaviour
{

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    //FIX detects only grunt
    private void OnTriggerEnter(Collider other)
    {
        //Get Tag Component
        Tags hitObject = other.GetComponent<Tags>();

        //Collisions
        if (hitObject.FindTag("boundary"))
        {
            //collision with wall
            Debug.Log("Hit a Wall");
            Destroy(gameObject);
        }
        else if (hitObject.FindTag("grunt"))
        {
            //collision with grunt
            Debug.Log("Hit a Grunt");
            Destroy(gameObject);
            Destroy(other); //<---- Deletes Boundary Collider (Should be destroying the game object of the grunt, instead destroys the colliders of barriers and the grunt)
        }
    }
}

这是自定义标签脚本

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

public class Tags : MonoBehaviour
{
    public string[] startTags;
    private static string[] tags;

    private void Start()
    {
        tags = startTags;
    }

    public bool FindTag(string search)
    {
        bool results = false;
        for (int i = 0; i < tags.Length; i++)
        {
            if(search == tags[i])
            {
                results = true;
                break;
            }
        }
        return results;
    }
}

Enemy Grunt Inspector

Wall Inspector

Projectile Inspector

【问题讨论】:

  • 使用CompareTag!
  • @derHugo 我认为他们的设计要求游戏对象可以使用一组标签进行标记,而不是一个或零个标签。

标签: c# unity3d


【解决方案1】:

看来你有两个问题。

1) 首先是你的射弹正在摧毁咕噜的对撞机,而不是咕噜。这是因为您将 collider 传递给了 destroy 函数,而不是 grunt:

Destroy(other);

改为使用

Destroy(other.gameobject);

我也会把这个放在前面

Destroy(gameObject);

2) 您的标签系统不工作。我猜这是因为

private static string[] tags;

是静态的。我会删除静态修饰符,看看它是否有效。您也可以直接使用startTags,无需分配start()

Unity 也已经有一个标签系统,可能更适合这种检测: https://docs.unity3d.com/Manual/Tags.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 2019-06-19
    • 2013-12-16
    相关资源
    最近更新 更多