Unity2D开发核心控制脚本
- 角色移动
- 场景切换
- 重新启动本场景
- 启动下一个场景
- 游戏暂停
角色移动
void Movement()
{
float horizontalmove = Input.GetAxis("Horizontal");
//获取整数
float facedircetion = Input.GetAxisRaw("Horizontal");
//角色移动
if(horizontalmove!=0)
{
rb.velocity = new Vector2(horizontalmove * speed * Time.fixedDeltaTime, rb.velocity.y);
anim.SetFloat("running", Mathf.Abs(facedircetion));
}
if(facedircetion!=0)
{
//控制人物反转
transform.localScale=new Vector3(facedircetion,1,1);
}
}
场景切换
重新启动本场景
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
代码解析
SceneManager.LoadScene() //启动场景,传入场景名字
SceneManager.GetActiveScene().name //现在正在激活的场景。名字
启动下一个场景
public void NextGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
.buildIndex //场景的绑定索引即编辑器左上角File->Build Settings,窗口上部的场景后面的索引值
游戏暂停
public void PauseGame()
{
pauseMenu.SetActive(true);
Time.timeScale = 0f;
}
从暂停状态切换至运行状态
public void ResumeGame()
{
pauseMenu.SetActive(false);
Time.timeScale = 1.0f;
}