Unity学习笔记:人物换装换武器

知识点:对数据的本地化存储和取用(PlayerPrefs 类)

诞生角色
using UnityEngine;
using System.Collections;

/// <summary>
/// 诞生角色
/// </summary>
public class BirthPlayer : MonoBehaviour
{
    private int clothIndex = 0;
    public GameObject player;
    public Texture[] cloth;
    private void Awake()
    {
        if (PlayerPrefs.HasKey("Cloth"))
            clothIndex = PlayerPrefs.GetInt("Cloth");
    }
    private void Start()
    {
        GameObject clone = 
            (GameObject)Instantiate(player, transform.position, transform.rotation);
        clone.GetComponentInChildren<SkinnedMeshRenderer>().material.mainTexture
            = cloth[clothIndex];
    }
 
}
更换服装
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

/// <summary>
/// 更换服装
/// </summary>
public class ChangeCloth : MonoBehaviour
{
    private SkinnedMeshRenderer clothRender;
    public Texture[] cloth;
    private int clothIndex = 0;
    private void Start()
    {
        clothRender = this.GetComponentInChildren<SkinnedMeshRenderer>();
    }
    private void OnGUI()
    {
        if (GUILayout.Button("服装01"))
        {
            clothRender.material.mainTexture = cloth[0];
            clothIndex = 0;
        }  
        if (GUILayout.Button("服装02"))
        {
            clothRender.material.mainTexture = cloth[1];
            clothIndex = 1;
        }
        if (GUILayout.Button("保存并进入游戏"))
        {
            PlayerPrefs.SetInt("Cloth", clothIndex);
            SceneManager.LoadScene("Game");
        }
    }
 
}

换武器

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

/// <summary>
/// 更换武器
/// </summary>
public class ChangeCloth : MonoBehaviour
{
    private SkinnedMeshRenderer clothRender;
    public Texture[] cloth;
    private int clothIndex = 0;
    public GameObject weapon;//武器
    private MeshFilter meshFilter;//武器网格组件
    private MeshRenderer weaponRender;
    public Mesh wpMesh;//武器网格
    public Texture wpTexture;//武器图片
    private void Start()
    {
        meshFilter = weapon.GetComponent<MeshFilter>();
        weaponRender = weapon.GetComponent<MeshRenderer>();

        clothRender = this.GetComponentInChildren<SkinnedMeshRenderer>();
    }
    private void OnGUI()
    {
        if (GUILayout.Button("服装01")) {
           //更换武器
            meshFilter.mesh = wpMesh;//换网格
            weaponRender.material.mainTexture = wpTexture;//换网格对应图片


            clothRender.material.mainTexture = cloth[0];
            clothIndex = 0;
        }  
        if (GUILayout.Button("服装02"))
        {
            clothRender.material.mainTexture = cloth[1];
            clothIndex = 1;
        }
        if (GUILayout.Button("保存并进入游戏"))
        {
            PlayerPrefs.SetInt("Cloth", clothIndex);
            SceneManager.LoadScene("Game");
        }
    }
 
}

猜你喜欢

转载自blog.csdn.net/huanyu0127/article/details/106087034