PlayerNameInputField.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="PlayerNameInputField.cs" company="Exit Games GmbH">
  3. // Part of: Photon Unity Networking Demos
  4. // </copyright>
  5. // <summary>
  6. // Let the player input his name to be saved as the network player Name, viewed by alls players above each when in the same room.
  7. // </summary>
  8. // <author>developer@exitgames.com</author>
  9. // --------------------------------------------------------------------------------------------------------------------
  10. using UnityEngine;
  11. using UnityEngine.UI;
  12. namespace Photon.Pun.Demo.PunBasics
  13. {
  14. /// <summary>
  15. /// Player name input field. Let the user input his name, will appear above the player in the game.
  16. /// </summary>
  17. [RequireComponent(typeof(InputField))]
  18. public class PlayerNameInputField : MonoBehaviour
  19. {
  20. #region Private Constants
  21. // Store the PlayerPref Key to avoid typos
  22. const string playerNamePrefKey = "PlayerName";
  23. #endregion
  24. #region MonoBehaviour CallBacks
  25. /// <summary>
  26. /// MonoBehaviour method called on GameObject by Unity during initialization phase.
  27. /// </summary>
  28. void Start () {
  29. string defaultName = string.Empty;
  30. InputField _inputField = this.GetComponent<InputField>();
  31. if (_inputField!=null)
  32. {
  33. if (PlayerPrefs.HasKey(playerNamePrefKey))
  34. {
  35. defaultName = PlayerPrefs.GetString(playerNamePrefKey);
  36. _inputField.text = defaultName;
  37. }
  38. }
  39. PhotonNetwork.NickName = defaultName;
  40. }
  41. #endregion
  42. #region Public Methods
  43. /// <summary>
  44. /// Sets the name of the player, and save it in the PlayerPrefs for future sessions.
  45. /// </summary>
  46. /// <param name="value">The name of the Player</param>
  47. public void SetPlayerName(string value)
  48. {
  49. // #Important
  50. if (string.IsNullOrEmpty(value))
  51. {
  52. Debug.LogError("Player Name is null or empty");
  53. return;
  54. }
  55. PhotonNetwork.NickName = value;
  56. PlayerPrefs.SetString(playerNamePrefKey, value);
  57. }
  58. #endregion
  59. }
  60. }