U3D武器系统切枪
多种武器切换教程
我们要通过鼠标来实现切枪效果,我们要有几种思路:
1、通过值来索引对应武器数组下标的值,然后生成,在切换武器的时候,先销毁当前的武器,在生成新武器。
2、直接先全部生成,状态全部不激活,通过值来实现具体激活哪一个。
我们这里讲第二种方法:
我们先在引擎里面添加几个对象,命名不同,充当武器,生成预制件。
在创建一个空物体,如图:
我们创建cutgun脚本,挂在空物体上
首先定义数组、集合
// An highlighted block
public GameObject[] weapons;//存放的武器
private List<GameObject> alweapons=new List<GameObject>();//实例化武器到集合里,集合的好处是集合长度是动态的。
private int i;//集合的下标值
在Start()里实例化
// An highlighted block
void Start()
{
i = 0;
for(int j = 0; j < weapons.Length; j++)
{
GameObject wea = Instantiate(weapons[j], transform.position, transform.rotation);//实例化
alweapons.Add(wea);//添加到集合里
}
Cutgun(i);//调用切枪的方法
}
写一个切枪的方法Cutgun(int *)
// An highlighted block
private void Cutgun(int num)
{
foreach (GameObject s in alweapons)//用foreach循环遍历集合
{
s.SetActive(false);//状态全部未激活
}
alweapons[num].SetActive(true);
}
我们在Update()里面通过滚轮改变下标的值
// An highlighted block
void Update()
{
if(Input.GetAxis("Mouse ScrollWheel") > 0)//滚轮向前滚代表是正值
{
i++;
if (i > alweapons.Count-1)//因为i是下标,下标的最大值就是集合长度-1
{
i = 0;
}
Cutgun(i);
}
else if(Input.GetAxis("Mouse ScrollWheel") < 0)
{
i--;
if (i <0)
{
i = alweapons.Count-1;
}
Cutgun(i);
}
}
完整代码
// An highlighted block
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cutgun : MonoBehaviour
{
public GameObject[] weapons;
private List<GameObject> alweapons=new List<GameObject>();
private int i;
// Start is called before the first frame update
void Start()
{
i = 0;
for(int j = 0; j < weapons.Length; j++)
{
GameObject wea = Instantiate(weapons[j], transform.position, transform.rotation);
alweapons.Add(wea);
}
Cutgun(i);
}
// Update is called once per frame
void Update()
{
if(Input.GetAxis("Mouse ScrollWheel") > 0)
{
i++;
if (i > alweapons.Count-1)
{
i = 0;
}
Cutgun(i);
}
else if(Input.GetAxis("Mouse ScrollWheel") < 0)
{
i--;
if (i <0)
{
i = alweapons.Count-1;
}
Cutgun(i);
}
}
private void Cutgun(int num)
{
foreach (GameObject s in alweapons)
{
s.SetActive(false);
}
alweapons[num].SetActive(true);
}
}
看下效果:
没有问题!!!