1

I want to be able to access a variable from one script using a variable in another script. For example, if I have one script that has this variable:

public bool Some_Name;

And in my other script I have this:

private string nameOfThingToGet = "Some_Name";
...
GameObject.Find ("Player").GetComponent <FirstScript> () .nameOfThingToGet = false;

Obviously this wont work, but how would I be able to do something like this?

3
  • Before you go down this road, have you considered making FirstScript expose a Dictionary<string, object> instead of using fields? This allows for GameObject.Find ("Player").GetComponent<FirstScript>().dictionary[nameOfThingToGet] = false; Commented Aug 2, 2017 at 18:16
  • Oh, I see thank you for your help. Commented Aug 2, 2017 at 18:17
  • That is what I did. got it working perfectly. Thanks again for the help. If you want to submit this as an answer to my question, I would mark it correct. Commented Aug 2, 2017 at 18:21

2 Answers 2

3

Before you go down this road, have you considered making FirstScript expose a Dictionary<string, object> instead of using fields?

This allows for you yo do

GameObject.Find("Player").GetComponent<FirstScript>().dictionary[nameOfThin‌​gToGet] = false;
Sign up to request clarification or add additional context in comments.

Comments

1

You can use reflection to achieve it.

var obj = GameObject.Find ("Player").GetComponent<FirstScript>();
FieldInfo myFieldInfo = obj.GetField(nameOfTheThingToGet, 
         BindingFlags.Instance);

For setting proper flags For reference you can visit here

1 Comment

I like the reflection solution but since this done in a game engine, Scott's is highly recommended. It's a matter of Dictionary vs Reflection performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.