How to get variable by name(string typed in inspector) in array with index from another script?
Hi! And sorry for my eng. I just learning to code and stuck with that problem - I have few buttons with some info about cost and level of selling properties. Each of them have next code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BuyBtns : MonoBehaviour
{
public SaveManager sData;
public Text lvl;
public Text buyCost;
public string varLvl; // I manually write the required variable name for each button in inspector
public string varCost; // And here too
void Start ()
{
lvl = gameObject.transform.GetChild(1).GetComponent<Text>();
buyCost = gameObject.transform.GetChild(2).GetComponent<Text>();
sData = GameObject.Find("PlayZone").GetComponent<SaveManager>();
}
public void RefreshInfo()
{
var lvlresult = sData.sv.GetType().GetField(varLvl).GetValue(sData.sv);
lvl.text = lvlresult.ToString();
}
}
I tried many different options for last method and this most successful with non-array variables. But i need to get value from array with index like [sData.sv.choosenShip] ?
However, i found another way. More combrous. But this gap in my knowledge been bugging me.
You're just learning to code?
People who are just learning to code should steer clear of reflection, typically speaking.
I think what you really want might be a Dictionary...
https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx
It stores key-value pairs of whatever type you like. For instance, Dictionary will store key-value pairs mapping strings to integers. You can use the keys like you would an index into an array. As in...
myDictionary["some string"] = 9;
var myInt = myDictionary["some string"];
Does that help at all?
This is what I was afraid of when come here. Ask a questions and get the answer not my level ))) I found a lot answers here that helped me with project. But today i got reflection(may laziness advised me to find a short way) and even don't fully understand what it is... Yet. But Thanks a lot! I'll try your advice!
Just to be clear, because there seems like a little language barrier is in place, I am advising you NOT to use reflection.
If you need to store and retrieve values based on a string key, my suggestion is that you use Dictionary (linked above).
Your answer
![](https://koobas.hobune.stream/wayback/20220612151815im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
[Quiz Game] How to prevent Question asked twice. HELP 1 Answer
Move enemy to a specific movepoint with an array (C#) 1 Answer
[common programming question] Custom array returns nothing 2 Answers
How to reference UI Panels, in an array for x and y? 0 Answers
Need help with 3d inventory system 0 Answers