unity切换武器2019-04-23
2019-04-23 本文已影响0人
愉快先生
文章末尾有weapon(武器切换)脚本和shooting(射击)脚本
- gameobject->creat empty child更名为weapons(新建一个空物体)
- weapon脚本
如下:
weapon 脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weapon : MonoBehaviour
{
//此脚本托给gameobject->creat empty child更名为weapons
public int count = 2;//用来判断按键次数
private void Start()
{
SelectWeapon(0);//默认第0把武器 枪
}
void SelectWeapon(int index) {//选择武器函数
for (var i = 0; i < transform.childCount; i++) {
if (i == index)
{
transform.GetChild(i).gameObject.SetActive(true);
}
else transform.GetChild(i).gameObject.SetActive(false);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.V))//判断按键V次数,调用selectweapon 方法
{
count=count+1;
if (count % 2 == 0)
{ SelectWeapon(0);
}
else
{
SelectWeapon(1);
}
}
Debug.Log(count);
}
}
shooting(开枪)脚本:
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
//子弹拖到场景成为预设。
//shooting脚本拖到gunend(枪口,空物体)
//传两个参数,一个是子弹,一个(gunEnd)枪口
public class shooting : MonoBehaviour
{
public Rigidbody prebullet;
public Transform gunEnd;
public int shellCount = 100;// 一个 弹夹的子弹数量
public Text bulletText;
private int score;
public Text scoreText;
void Start()
{
score = 0;
}
// Update is called once per frame
void Update()
{
if (shellCount > 0) { shootbullet(); }
else {
Debug.Log("没子弹了");//!!!直接退出程序,要完善!!!
}
}
void shootbullet()
{//开火::生成一大堆子弹,把前面的都复制了,原因是我绑到了子弹上
if (Input.GetButtonDown("Fire1"))
{
Debug.Log("biubiubiu");
Rigidbody bulletini;
bulletini = Instantiate(prebullet, gunEnd.position, gunEnd.rotation);
bulletini.AddForce(gunEnd.forward * 1200);// 加速度AddForce函数,这里速度过快会把模型穿透
Destroy(bulletini.gameObject, 5); //销毁子弹
shellCount--;
bulletText.text = shellCount.ToString();//转成文字类型,报错,要在属性中指定一下
}
}
public void AddScore(int newScore)
{
score += newScore;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = " " + score;
}
}