所以我试图为我的2d自上而下的太空射击游戏改变武器。通过武器我只是意味着我的子弹预制,所以它射出一个不同的子弹,然后我可以增加损坏等。
这是我的代码。当我按下数字2时,它会在层次结构中拍摄我的预制克隆,但它的灰色显示并且在游戏视图中没有显示任何内容。以下是我的播放器拍摄代码。
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);
}
}
}
答案 0 :(得分:1)
保持其余代码相同,只需更改以下行
即可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)时,预制件将停用。这导致被激活的GameObjects被实例化。
我建议你做的是有两个单独的预制件并相应地产生它们。