Search Unity

Character choose menu

Discussion in 'Scripting' started by Deleted User, May 27, 2017.

  1. Deleted User

    Deleted User

    Guest

    Hello all, I'm a new in Unity and Im just making my first game. I would like to ask you or maybe u can advice me something. I made prototype script for character choose menu and I would like to hear your opinion about it. It's work good, as on me, but say me please what you think about it?

    The first script is:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class SelectScript : MonoBehaviour {
    4.  
    5.     int splayer = 1;
    6.  
    7.     public void SPlayer()
    8.     {
    9.         splayer = 1;
    10.         PlayerPrefs.SetInt("SPlayer", splayer);
    11.         print("player1 selected");
    12.     }
    13.     public void SPlayer2()
    14.     {
    15.         splayer = 2;
    16.         PlayerPrefs.SetInt("SPlayer", splayer);
    17.         print("player2 selected");
    18.     }
    19. }
    20.  
    The second part of script that attached to player and change player on start of scene:

    Code (CSharp):
    1. private void Start()
    2.     {
    3.         if (PlayerPrefs.GetInt("SPlayer") == 1)
    4.         {
    5.             GameObject.Find("Player").SetActive(true);
    6.             GameObject.Find("Player2").SetActive(false);
    7.         }
    8.         if (PlayerPrefs.GetInt("SPlayer") == 2)
    9.         {
    10.             GameObject.Find("Player2").SetActive(true);
    11.             GameObject.Find("Player").SetActive(false);
    12.         }
    13.     }
     
  2. Deleted User

    Deleted User

    Guest

    And, sorry for my English, I hope u will understand me))
     
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Looks good, no problems there. That's one valid way of doing things.
    I'd say one piece of good advice for your script (for a change) , though, would be to make references to "Player" and "Player2" at the top of your script/class. Either public variables, or with the SerializeField attribute (which is private but can be viewed in the inspector). After that, drag & drop the Player + Player2 objects to those fields. This would replace your GameObject.Find calls. It's more efficient (and faster). You should avoid GameObject.Find and its variations as much as possible (or completely if you can:)).
     
  4. Deleted User

    Deleted User

    Guest


    Don't know how could I forget about SerializeField:(... It's good idea, thank you very much for your reply, you gave me good advice and I will try to make it.
    Thank you and good day!;)
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    No problem. :) You have a good day, too!
     
    Deleted User likes this.