Best Approach to manage unity UI

Viewed 45

I'm developing games for almost 1 year but the code for UI elements is the most painful part of my game dev. Making UI is working is pretty easy although it's a lot of work to do it seems like I'm writing the same code again and again. Here is some code example that'll help you understand what I'm trying to convey to you

public Slider volume; //let suppose i have too many sliders
public float volume_val;

private Toggle soundToggler;// let suppose i have too many Toggle
public bool isMuted;

private Text coinText; // let suppose i have too many Text
public float coins;

// let suppose i have too many XYZ fields

private void Awake ()
{

  volume_val = PlayerPrefs.GetFloat ("volume_val");
  volume.value = volume_val;
  volume.onValueChanged.AddListener ( (newVolume) => {
   volume_val = newVolume;
   PlayerPrefs.SetFloat ("volume_val", volume_val);
  });

  isMuted = PlayerPrefs.GetInt ("isMuted") == 1 ? true : false;
  soundToggler.isOn = isMuted;
  soundToggler.onValueChanged.AddListener ((newVal)=> {
   isMuted = newVal;
   PlayerPrefs.SetInt ("isMuted", isMuted ? 1 : 0);
  });
  
  coins = PlayerPrefs.GetFloat ("coins");
  coinText.text = coins;
  // update text on value update
}

As you can see by the code I'm repeating the same code, again and again, is there any generic way to do this?

1 Answers

Writing a clean and efficient code is an art and one can learn it by only practice.

There are some practices you can follow while developing with unity, not limited to ui development only..

1. You should follow the naming standards for the better readability of the code. This will also make your code more clean and any changes would be easy.

2. Create methods for each task in your script. This will promote better readability of your code. Writing all the ui code in Awake is not good programming practice with unity.

3. Your code should be loosely coupled, modular and scalable.

4. Try SOLID principles and Design Principles, that will help a lot as a programmer and also makes your code clean, scalable, and modular. It also helps a lot in debugging. There are lots of resources available on the internet for learning and implementing these principles in unity.

Very specific to your problem, this post may help you. You can also use Expression body definitions to make your code more readable and concise.

Related