如何禁用数组中的某些对象?

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

我有一个用于切换喷枪的脚本,它有一个数组来获取所有元素的MeshRenderer组件,然后,我可以启用我想要的元素,但不能禁用其他元素。

public class TrocarArma : MonoBehaviour
{
    [Header("References")]
    public int choosenGun = 0;
    [Space(10)]
    [SerializeField] MeshRenderer[] meshes = new MeshRenderer[4];

    void Start()
    {
        SelectWeapon();
    }

    void Update()
    {
        ChangeGun();
    }

    void SelectWeapon()
    {
        int gunCount = 0;                                                             

        meshes[0] = GameObject.Find("GravityGun").GetComponent<MeshRenderer>();
        meshes[1] = GameObject.Find("IronBar").GetComponent<MeshRenderer>();
        meshes[2] = GameObject.Find("Tablet").GetComponent<MeshRenderer>();
        meshes[3] = null;                                                      //Will be filled later.

        foreach(Transform gun in transform)
        {
            if (gunCount == choosenGun)
            {
                meshes[choosenGun].enabled = true;
            }
            else
            {
                 ///Code to make the others array meshes elements MeshRenderers disable.
            }

            gunCount++;
        }
    }

    void ChangeGun()
    {
        int previousWeapon = choosenGun;

        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            if(choosenGun >= transform.childCount -1)
            {
                choosenGun = 0;
            }
            else
            {
                choosenGun++;
            }
        }
        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            if (choosenGun <= 0)
            {
                chooseGun = transform.childCount - 1;
            }
            else
            {
                chooseGun--;
            }
        }

        if (previousWeapon != chooseGun)
        {
            SelectWeapon();
        }
    }
}

我只是不使用SetActive(true)/(false),因为我需要激活我的平板电脑来升级防御。我制作此脚本的视频:https://www.youtube.com/watch?v=Dn_BUIVdAPg,感谢您的阅读!

c# arrays unity3d
1个回答
0
投票

void SelectWeapon()方法内部有奇怪的逻辑。但是,我敢建议以下代码可以为您提供帮助:

foreach(Transform gun in transform)
{
    if (gunCount == choosenGun)
    {
        meshes[choosenGun].enabled = true;
    }
    else
    {
        meshes[gunCount].enabled = false;
    }

    gunCount++;
}

foreach(Transform gun in transform)
{           
    switch(gunCount)
    {
        case 0:
            meshes[choosenGun].enabled = true;
            break;

        default:
            meshes[gunCount].enabled = false;
            break;
    }

    gunCount++;
}
© www.soinside.com 2019 - 2024. All rights reserved.