首页 > 解决方案 > 粒子系统仅在 GetButton() 的开始和结束时播放

问题描述

我正在制作一个 FPS,下面是我的 GunScript:

{
    public float damage = 10f;
    public float range = 100f;
    public float fireRate = 5f;
    public float impactForce = 30f;

    public Camera playerCam;
    public ParticleSystem muzzleFlash;
    public GameObject impactEffect;

    private float nextTimeToFire = 0f;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
        {
            nextTimeToFire = Time.time + 1f / fireRate;
            Shoot();
        }
    }

    void Shoot()
    {
        muzzleFlash.Play();

        RaycastHit hit;
        if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range))
        {
            Debug.Log(hit.transform.name);

            Target target = hit.transform.GetComponent<Target>();
            if (target != null)
            {
                target.TakeDamage(damage);
            }

            if (hit.rigidbody != null)
            {
                hit.rigidbody.AddForce(-hit.normal * impactForce);
            }

            Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
        }
    }
}

然而,粒子系统仅在我按下鼠标或抬起鼠标时播放。当我的鼠标被按下时,它应该连续播放。请帮助我,并提前感谢。

标签: c#unity3dvisual-studio-codeparticle-system

解决方案


我认为这里的问题是您只在方法中播放它,该Shoot()方法仅在每次开火时调用,但我不知道您的粒子系统是什么样的。如果你想让它连续播放,你应该把它放在Shoot()方法之外的一个单独的 if 语句中,Update()或者像这样修改它:

if (Input.GetButton("Fire1"))
{
    muzzleFlash.Play();
    if (Time.time >= nextTimeToFire) 
    {
        nextTimeToFire = Time.time + 1f / fireRate;
        Shoot();
    }
}

推荐阅读