using a string as variable in different script?

So this is all in c#
In script A i will have variables i.e.
int bomb1 = 20;
int bomb2 = 10;
int bomb3 = 35; and so on

so in the script i would have something like this:

void setDamageAmount(string dAmount){
    //relate dAmount to the variable name above get the int
}

So basically script B calls the function in Script A passing say “bomb2”, and then in script A i need to take dAmount which now equals “bomb2” and get what bomb2 equals in the variables. It should be 10?

Two approaches spring to mind:

Dictionary for Named Properties:

using UnityEngine;
using System.Collections.Generic;

public class ScriptA : MonoBehaviour {
    private Dictionary<string, int> _intProperties = new Dictionary<string, int>();
    public IDictionary<string, int> IntProperties {
        get { return _intProperties; }
    }
}

Then your other script can do this:

var a = go.GetComponent<ScriptA>();
a.IntProperties["bomb1"] = 42;

if (a.IntProperties.ContainsKey("bomb2"))
    Debug.Log(a.IntProperties["bomb2"]);

Reflection: (Slower)

var a = go.GetComponent<ScriptA>();

var bomb1Field = a.GetType().GetField("bomb1");
bomb1Field.SetValue(a, 42);

I haven’t had time to test the above, but hopefully you should get the basic idea.

I hope that you find this useful :slight_smile:

Not home right now, but I dont quite understand how add to the dictionary.