Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question How can I use the data stored in one variable to reference another?

Discussion in 'Scripting' started by nomatt55, May 3, 2024.

  1. nomatt55

    nomatt55

    Joined:
    Mar 25, 2024
    Posts:
    4
    Hello,

    Let's say that I have one variable that is equal to the name of the GameObject that the script is attached to. I have a static variable that is declared elsewhere. I want to find the static variable that has the same name as the string stored in my first variable. How can this be done?

    I want it so that I can have one script manage all of my text elements. I want "PerkName1" to change its text to the string value of the static variable "PerkName1". If anyone has a better idea than storing the name of the Text element as a variable, please enlighten me.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,931
    You just shouldn't do this. There are much better ways than using GameObject names and trying to reflect on the name of the variable. You are probably coming from Python or JavaScript where such techniques are common, but there are more efficient ways.

    You can/should learn how to use a Dictionary in C#, which can be used to map a string to your UI Text element for example.