Updating GameObject Variables in Script
I've done a lot of searching on this topic and can't find the answer to my question. It may be something obvious but I am relatively new to Unity, coming from a strong background in other programming languages/environments.
This issue I have is how do you modify or work with a game object's variables or functions through the script that is attached to it. I.E. lets say I have a music volume slider. I know that if I want to update the stored volume value I can do the following:
private void Update ()
{
GameManager.Instance.music_volume = music_slider.value;
}
The above works fine for storing the value from the slider into my game manager singleton class which then updates the user player preferences. This issue I can't wrap my head around is how do I get "music_slider" to reference the Slider Game Object that the script is attached to.
This has been my solution so far but it just doesn't feel right, any suggestions?
private Slider music_slider; // Internal Slider Reference
private void Awake()
{
// Internal slider reference is always to the Slider Game Object that the script is attached to.
music_slider = this.gameObject.GetComponent<Slider>();
}
For complete clarity here is the full structure of my script class that is attached to a MusicVolumeSlider
public class MusicSliderControl : MonoBehaviour
{
private Slider music_slider; // Internal Slider Reference
private void Awake()
{
// Internal slider reference is always to the Slider Game Object that the script is attached to.
music_slider = this.gameObject.GetComponent<Slider>();
}
// Use this for initialization
private void Start ()
{
music_slider.value = GameManager.Instance.music_volume;
}
// Update is called once per frames
private void Update ()
{
GameManager.Instance.music_volume = music_slider.value;
}
}
GetComponent is how you access components when you know the object they're attached to. So in this case, if the slider is attached to the same object as this script, all you need to do is;
music_slider = GetComponent<Slider>();
Ah okay so I don't need "this.gameObject" in order to use "GetComponent". By calling "GetComponent<>()" in the script it will automatically reference the game object that the script is attached to?
Your answer
Follow this Question
Related Questions
Minesweeper - Surrounding Objects - C# 0 Answers
this.GetComponent() won't return gameObject? How to get it without using this.gameObject? 3 Answers
Find a specific object using transform 0 Answers
Why Does Prefab Loose UI elements on Scene Change 0 Answers
I have searched like the whole Internet for this lol (get Value of specific Prefab(clone)) 2 Answers