首页 > 解决方案 > 使积分收集并转到其他地方的脚本,使用“itrigger”标签影响所有内容

问题描述

我遇到了一些麻烦,每次我用带有触发器的对撞机撞到任何东西时,它都会产生一个点并删除具有触发器的对象,我正在考虑向可收集点添加一个图层或标签该脚本将检测并仅影响带有标签或图层的对象,但无法弄清楚这一点。

这是我的代码

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

public class Collect : MonoBehaviour
{
    private Rigidbody2D rb;

    [SerializeField]
    private GameObject Point;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        SpawnPoint();
    }

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

    private void FixedUpdate()
    {
    }

    private void SpawnPoint()
    {
        bool pointSpawned = false;
        while (!pointSpawned)
        {
            Vector3 pointPosition =  new Vector3(Random.Range(-13f, 13f), Random.Range(-8f, 8f), 0f);
            if ((pointPosition - transform.position).magnitude <  3)
            {
                continue;     
            }
            else
            {
                Instantiate(Point, pointPosition, Quaternion.identity);
                pointSpawned = true;
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Destroy(collision.gameObject);
        SpawnPoint();
    }
}

标签: c#unity3dtriggers

解决方案


您可以使用该CompareTag功能检查对象是否属于某个标签。

试试这个:

OnEnterTrigger2D(Collider2D collision)
{
    if(collision.collider.gameobject.CompareTag("The tag you want to compare"))
    {
        Destroy(collision.gameObject);
        SpawnPoint();
    }
}

推荐阅读