- Home /
Request feedback for C# script (instantiating UI elements depending on Player Input)
Dear Community,
I am very new to Unity and to scripting. I have created a scene with UI elements exclusively. It works but my script "GameManager" that manages it all seems very complicated to me. I was hoping someone out there would be willing to give me feedback, maybe even suggest a better way, if there is one. I am struggling with the basics of C# and efficiency.
In the scene you can write the number of Players into an input field (picture not taken in play mode):
This prompts as many input fields to spawn, in which you can write the names of the Players (picture taken in play mode):
Having done so and pressing a "FinishedButton", these names are allocated to a list of "PlayerNames" and the screen switches to a different canvas (menu2). As I sad, it works but it seems so complicated to me. This is the "GameManager" script on the "Main Camera":
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour {
//two canvases. One for picking number of players and their names. Second for the game.
public GameObject menu1;
public GameObject menu2;
//Stuff to pick number of players and their names. All on the first canavas.
public InputField pickNumberOfPlayers;
private int numberOfPlayers = 0;
public GameObject playerNamesPanel;
public InputField pickPlayerNamePrefab;
public List<InputField> pickPlayerNameClones;
public List<string> playerNames;
public GameObject finishedButton;
// method for the InputField to choose the number of players
public void NumberOfPlayersPicked()
{
numberOfPlayers = int.Parse(pickNumberOfPlayers.text);
pickNumberOfPlayers.interactable = false;
for (int i = 0; i < numberOfPlayers; i++)
{
pickPlayerNameClones.Add (Instantiate (pickPlayerNamePrefab));
pickPlayerNameClones [i].transform.SetParent (playerNamesPanel.transform, false);
}
playerNamesPanel.SetActive (true);
finishedButton.SetActive (true);
}
// method for the final button that will assign the names in the input fields to the List playerNames
// and switch to the game canvas "menu2"
public void PlayerNamesPicked()
{
if (numberOfPlayers != 0)
{
for (int i = 0; i < numberOfPlayers; i++) {
playerNames.Add (pickPlayerNameClones [i].text);
}
menu1.SetActive (false);
menu2.SetActive (true);
}
Debug.Log (playerNames [0]);
}
}
Thank you in advance.