OK,先上图,点击prev选项上一个游戏对象,点击nex选择下一个游戏对象
using
UnityEngine
;
using
UnityEngine
.
UI
;
///
<summary>
///
游戏对象的上下顺序选择
///
</summary>
public
class
CharacterCreation
:
MonoBehaviour
{
///
<summary>
///
可供选择的游戏对象数组
///
</summary>
public
GameObject
[]
characterPrefabs
;
///
<summary>
///
储存实例化出来的游戏对象数组
///
</summary>
private
GameObject
[]
characterGameObject
;
///
<summary>
///
当前选择的游戏对象的索引
///
</summary>
private
int
selectedIndex
= 0;
///
<summary>
///
所有可供选项的游戏对象的个数
///
</summary>
private
int
length
;
///
<summary>
///
选择上一个游戏对象Button
///
</summary>
private
Button
PrevButton
;
///
<summary>
///
选择下一个游戏对象Button
///
</summary>
private
Button
NexButton
;
void
Awake
()
{
// 获取到选择button的引用
//获取到往上选择button组件
PrevButton
=
GameObject
.
Find
(
"ButtonPrev"
).
GetComponent
<
Button
>();
//获取到往下选择button组件
NexButton
=
GameObject
.
Find
(
"ButtonNex"
).
GetComponent
<
Button
>();
}
void
Start
()
{
//调用初始化时实例化游戏对象的方法
CharacterGameObject
();
//调用更新所有游戏对象的显示与隐藏方法
UpdateCharacterShow
();
}
///
<summary>
///
start执行后执行,绑定button事件
///
</summary>
void
OnEnable
()
{
//清除默认监听事件
NexButton
.
onClick
.
RemoveAllListeners
();
//绑定往上选择点击事件
NexButton
.
onClick
.
AddListener
(
OnNexButtonClick
);
//清除默认监听事件
PrevButton
.
onClick
.
RemoveAllListeners
();
//绑定往上选择点击事件
PrevButton
.
onClick
.
AddListener
(
OnPrevButtonClick
);
}
///
<summary>
///
Start开始时调用,实例化游戏对象
///
</summary>
void
CharacterGameObject
()
{
//获取到当前可供选择的游戏对象的总数
length
=
characterPrefabs
.
Length
;
//实例化当前储存的游戏对象数组,游戏对象数量等于可供选择的总数,length
characterGameObject
=
new
GameObject
[
length
];
//循环遍历创建游戏对象
for
(
int
i
= 0;
i
<
length
;
i
++)
{
characterGameObject
[
i
] =
Instantiate
(
characterPrefabs
[
i
],
transform
.
position
,
transform
.
rotation
)
as
GameObject
;
}
}
///
<summary>
///
更新所有游戏对象的显示与隐藏
///
</summary>
void
UpdateCharacterShow
()
{
//默认设置第一个游戏对象显示
characterGameObject
[
selectedIndex
].
SetActive
(
true
);
//循环遍历游戏对象的显示与隐藏
for
(
int
i
= 0;
i
<
length
;
i
++)
{
//如果当前游戏对象不是被选择的,设为隐藏
if
(
i
!=
selectedIndex
)
{
//把未选择的游戏对象设置为隐藏
characterGameObject
[
i
].
SetActive
(
false
);
}
}
}
///
<summary>
///
选择上一个游戏对象
///
</summary>
public
void
OnPrevButtonClick
()
{
//当点击下一个游戏对象时,selectedIndex开始--,默认从0开始
selectedIndex
--;
//判断,如果当前选择游戏对象selectedIndex等于-1的时候
if
(
selectedIndex
== -1)
{
//设置当前选择游戏对象的索引为默认0,不能往上选择
selectedIndex
= 0;
}
//更新当前显示与隐藏的游戏对象
UpdateCharacterShow
();
}
///
<summary>
///
选择下一个游戏对象
///
</summary>
public
void
OnNexButtonClick
()
{
//当点击下一个游戏对象时,selectedIndex开始++,默认从0开始
selectedIndex
++;
//往下选择,循环选择
//判断当前所有是否超出边界,索引从0开始,最大值是length-1
selectedIndex
%=
length
;
/*当选择了最后一个游戏对象时,不能循环选择,只能往上选择
if (selectedIndex>length-1)
{
selectedIndex = length - 1;
}*/
//更新当前显示与隐藏的游戏对象
UpdateCharacterShow
();
}
}