Using GameObject.Tag

本文关键字:Tag GameObject Using | 更新日期: 2023-09-27 18:17:47

我想看看我们目前装备了什么枪,并播放特定的枪声,我正在搜索武器的标签。然而,我得到的错误'类型PlayerWeapon不包含标签的定义,没有类型PlayerWeapon的扩展方法标签可以找到'。

这是playershoot脚本附加到播放器预制处理标签的部分:

        weaponManager = GetComponent<WeaponManager>();
    }
    void Update ()
    {
        currentWeapon = weaponManager.GetCurrentWeapon();
        if (PauseMenu.IsOn)
            return;
        if (currentWeapon.fireRate <= 0f)
        {
            if (Input.GetButtonDown("Fire1"))
            {
                Shoot();
                if(currentWeapon.tag = "Tec")
                {
                    CmdPlayTecShootSound();
                }
            }

这是武器库脚本的相关部分:

private PlayerWeapon currentWeapon;
    private WeaponGraphics currentGraphics;
    private Transform currentHolder;
    void Start ()
    {
        currentHolder = awpweaponHolder;
        EquipWeapon(primaryWeapon);
    }
    void Update()
    {
        if(Input.GetAxis("WeaponSwitch") >0f)
        {
            currentHolder = tecweaponHolder;
            EquipWeapon(secondaryWeapon);
            Debug.Log("switched weapon");
        }
        else if (Input.GetAxis("WeaponSwitch")<0f)
        {
            currentHolder = awpweaponHolder;
            EquipWeapon(primaryWeapon);
            Debug.Log("switched weapon back");
        }
    }
    public PlayerWeapon GetCurrentWeapon ()
    {
        return currentWeapon;
    }
    public WeaponGraphics GetCurrentGraphics()
    {
        return currentGraphics;
    }
    void EquipWeapon (PlayerWeapon _weapon)
    {
        foreach (Transform child in tecweaponHolder)
        {
            Destroy(child.gameObject);
        }
        currentWeapon = _weapon;
更新:

void Update ()
    {
        currentWeapon = weaponManager.GetCurrentWeapon();
        if (PauseMenu.IsOn)
            return;
        if (currentWeapon.fireRate <= 0f)
        {
            if (Input.GetButtonDown("Fire1"))
            {
                Shoot();
                foreach (Transform child in tecweaponHolder)
                {
                    if(gameObject.tag == "Tec")
                    {
                        CmdPlayTecShootSound();
                        Debug.Log("tec sound played");
                    }
                }
                foreach (Transform child in awpweaponHolder)
                {
                    if(gameObject.tag == "Awp")
                    {
                        CmdPlayAwpShootSound();
                        Debug.Log("awp sound played");
                    }
                }
            }

Using GameObject.Tag

currentWeapon是一个附加到GameObject的脚本实例。要获得标签,您必须首先将其转换为GameObjectTransform,然后获得标签名称。

也可以比较多个=符号,而不是一个。你分配一个=符号。

if(currentWeapon.tag = "Tec") 应为 if (currentWeapon.gameObject.tag == "Tec")

最后,出于性能原因,应该使用CompareTag函数来compare标记。

使用currentWeapon.gameObject.tag获取标签的名称。例如:Debug.Log("Tag: " + currentWeapon.gameObject.tag);

然后使用if (currentWeapon.gameObject.CompareTag("Tec")){}比较标签