统一改变 weapons.prefab 问题

unity changing weapons.prefab issues

所以我正在尝试为我的 2d 自上而下 space 射手更换武器。武器我只是指我的子弹预制件所以它射出不同的子弹然后我可以增加伤害等等

这是我的代码。当我按数字 2 时,它会在层次结构中拍摄我的预制克隆,但它会变灰,并且游戏视图中没有任何显示。下面是我的 playerShoot 代码。

public class playerShoot : MonoBehaviour {

public Vector3 bulletOffset = new Vector3 (0, 0.5f, 0);
float cooldownTimer = 0;
public float fireDelay = 0.25f;
public GameObject bulletPrefab;
int bulletLayer;

public int currentWeapon;
public Transform[] weapons;

void Start () {

}

void Update () {

    if (Input.GetKeyDown(KeyCode.Alpha1)){
        ChangeWeapon(0);

    }
    if (Input.GetKeyDown(KeyCode.Alpha2)){
        ChangeWeapon(1);

    }

    cooldownTimer -= Time.deltaTime;
    if (Input.GetButton("Fire1") && cooldownTimer <= 0){
        cooldownTimer = fireDelay;
        Vector3 offset = transform.rotation * bulletOffset;
        GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, transform.position + offset, transform.rotation);
        bulletGO.layer =gameObject.layer;
    }


}

public void ChangeWeapon(int num){
    currentWeapon = num;
    for (int i = 0; i < weapons.Length; i++){
        if (i ==num)
            weapons[i].gameObject.SetActive(true);
        else
            weapons[i].gameObject.SetActive(false);
    }
}

}

保持其余代码不变,只需更改以下行

GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, transform.position + offset, transform.rotation);

GameObject bulletGO = (GameObject)Instantiate(weapons[currentWeapon].gameObject, transform.position + offset, transform.rotation);

所做的更改是对武器阵列中的武器使用变换,而不是使用 bulletPrefab。

出现问题是因为您正在实例化一个预制件,它与您用于武器阵列中第一个元素的变换相同。因此,当您调用 ChangeWeapon(1) 时,预制件将被停用。这导致实例化了不活动的游戏对象。

我建议你做的是有两个单独的预制件并相应地生成它们。