一、遊戲場景的轉換並持久化數據
在上一篇文章中,開始界面的腳本基本完成,那麼接下來就是開始遊戲,進入遊戲場景。
1、遊戲場景轉換
場景的切換我們需要用到以下代碼
SceneManager.LoadScene(string sceneName);
提示:如果場景切換失敗,請點擊File->Build Setting… 檢查Scenes In Build窗口中是否有你需要轉換的場景。
在OGUI的佈局上,我們再添加一個按鈕StartGame,此按鈕的作用就是用來進行場景的轉換,事件如何添加就不再進行敘述了。
2、持久化數據
不明白持久化數據(PlayerPrefs)如何使用的,建議瞭解一下,鏈接如下
接下來就是持久化數據(PlayerPrefs),將開始界面所選擇的人物、武器、衣服,做上標記,然後在遊戲場景當中進行創建。
具體步驟: 在武器選擇、人物選擇、服裝選擇的腳本上,分別添加一個靜態屬性用於存儲當前是選擇了何種類型的武器、人物、服裝(在上一篇的角色腳本中已經添加了),然後在StartName的按鈕上添加一個腳本,在點擊此按鈕時,腳本將另三個腳本中的靜態屬性取出,進行持久化存儲,並進入到下一個遊戲場景當中。
- 在選擇武器的腳本上,添加weapon靜態屬性,用於記錄選擇的武器
- 如何記錄:在創建遊戲物體時,給靜態屬性進行賦值
- 在按鈕StartGame的腳本上進行持久化數據,注意:只有當點擊腳本的時候才進行持久化存儲,所以在點擊事件當中進行。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class StartGame : MonoBehaviour
{
private void Start()
{
GetComponent<Button>().onClick.AddListener(new UnityAction(ToPlay));
}
private void ToPlay()
{
if (GenerateRole.Role!=null&& WeaponChose.Weapon!=null&& ChoseCloth.Cloth!=null)
{
PlayerPrefs.SetString("Role", GenerateRole.Role.name);
PlayerPrefs.SetString("Weapon", WeaponChose.Weapon.name);
PlayerPrefs.SetString("Cloth", ChoseCloth.Cloth.name);
SceneManager.LoadScene("UCP Demo Scene");
}
else
{
Debug.Log("請先選擇角色、武器、服裝");
}
}
}
二、角色創建與移動
1、角色創建
- 角色的創建需要根據PlayerPrefs類獲取的字符串來獲取資源,我們使用Resourse類的Load(string path)方法來獲取資源(使用此方法獲取資源,資源文件的路徑必須在Resourse文件夾下);在得到資源後,我們使用Instantiate在遊戲場景中進行創建,代碼如下(僅供參考):
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class CreateRole : MonoBehaviour
{
private GameObject role;
private GameObject weapon;
private Texture cloth;
private Transform weaponLocal;
//角色物體創建的位置
public Transform roleLocal;
private void Start()
{
//Debug.Log("角色名:"+PlayerPrefs.GetString("Role"));
//Debug.Log("武器名:"+PlayerPrefs.GetString("Weapon"));
//Debug.Log("服裝名:"+PlayerPrefs.GetString("Cloth"));
//獲取的角色名字和武器名字是帶有(Clone)的,所以進行字符串切割.
//role = Resources.Load<GameObject>("GameRole/MonsterBaseTeam/3D/mon_goblinWizard/mon_goblinWizard");
GenerateRole();
}
//切割字符串
private string SplitName(string name)
{
return name.Substring(0, name.IndexOf("("));
}
private string path = @"GameRole\MonsterBaseTeam";
/// <summary>
/// 加載武器資源
/// </summary>
/// <param name="name"></param>
private void LoadResourse(string name)
{
string newPath;
newPath = Path.Combine(path, "3D\\weapons", SplitName(name));
weapon=Resources.Load<GameObject>(newPath);
Debug.Log("武器路徑"+newPath);
}
//這裏之所以要將資源加載區分開來,是因爲我的資源路徑有點複雜(代碼僅供參考哦)
/// <summary>
/// 加載人物和武器資源
/// </summary>
/// <param name="roleName">角色名字</param>
/// <param name="clothName">服裝名字</param>
private void LoadResourse(string roleName,string clothName)
{
string rolePath;
string clothPath;
rolePath = Path.Combine(path, "Prefabs");
clothPath = Path.Combine(path, "3D",SplitName(roleName), clothName);
rolePath = Path.Combine(rolePath, SplitName(roleName));
role=Resources.Load<GameObject>(rolePath);
cloth=Resources.Load<Texture>(clothPath);
Debug.Log("服裝路徑:"+clothPath);
}
/// <summary>
/// 創建角色物體
/// </summary>
private void GenerateRole()
{
//加載資源
LoadResourse(PlayerPrefs.GetString("Weapon"));
LoadResourse(PlayerPrefs.GetString("Role"), PlayerPrefs.GetString("Cloth"));
GameObject ro = Instantiate(role, roleLocal.position, Quaternion.Euler(0,180,0));
//設置武器創建的位置
weaponLocal = GameObject.Find("wphand").transform;
GameObject wea=Instantiate(weapon,weaponLocal.position, Quaternion.Euler(0, -105, 150));
wea.transform.SetParent(weaponLocal);
ro.GetComponentInChildren<Renderer>().material.mainTexture = cloth;
ro.transform.SetParent(GameObject.Find("BirthPlace").transform);
//給創建的角色添加碰撞器組件,剛體組件
ro.AddComponent<BoxCollider>();
ro.GetComponent<BoxCollider>().size =new Vector3(2,5,1);
}
}
2、角色移動
- 可創建一個空物體,給物體添加一個組件character controller,角色控制器按鈕,並創建一個相機作爲這個空物體的子類。編寫一個移動腳本掛載到空物體上,物體就能移動跳躍了,通過控制組件character controller的屬性可以調整跳躍高度等,腳本如下(此腳本要和組件character controller一起):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoleMove : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
三、角色動畫添加
- 需要添加的動畫有走、跑、死亡、攻擊、待機。
因爲要設置播放動畫,那麼就需要獲取Animation組件(我這裏使用的是animation組件,你們可以嘗試使用Animator組件,即Mecanim動畫系統)
在角色物體還未創建時,我們是找不到動畫組件的,所以我們需要先讓尋找組件的方法等待一會再進行查找,而在Update方法中調用的方法需要使用到此組件,所以我們使用協程來進行等待一會,兩個等待時間是有關聯的,必須先找到組件再執行Update中的方法。
- 代碼如下(僅供參考):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayAction : MonoBehaviour
{
private Animation ani;
//存儲wsad輸入的值
private float x;
private float y;
private void Start()
{
//三秒後調用查找組件方法,是確保創建遊戲角色的腳本在此之前運行了
Invoke("FindComponent", 0.8f);
}
private void Update()
{
StartCoroutine(ControllAction());
}
/// <summary>
/// 查找子類中Animation的組件
/// </summary>
private void FindComponent()
{
ani = transform.GetComponentInChildren<Animation>();
}
/// <summary>
/// 控制動畫播放
/// </summary>
private IEnumerator ControllAction()
{
//協程進行等待,確保ani已經找到組件
yield return new WaitForSeconds(1);
if (ani != null)
{
x = Input.GetAxis("Horizontal");
y = Input.GetAxis("Vertical");
if (x != 0 || y != 0)
{
ani.Play("Run");
}
else if (ani.IsPlaying("Run"))
ani.CrossFade("Idle");
else ani.CrossFadeQueued("Idle");
if (Input.GetMouseButtonDown(0))
{
ani.Play("Attack01");
}
else if (Input.GetMouseButtonDown(1))
{
ani.Play("Attack02");
}
}
else Debug.Log("Animation組件爲空!");
}
}
- 到此爲止,我們的角色終於是誕生能跑能跳了,接下來就是打怪了。
打怪功能的實現請見 Unity3D-----簡易遊戲項目開發03