How to access the value of a bool in another script c#?

script 1:

public bool Enabled;

if (Input.GetKeyUp(KeyCode.Escape))
{

Enabled = !Enabled;

}

script 2:

if (!Enabled)
{

debug.log (“ESC has been pressed”);

}

My problem is that the second script doesn’t know what Enabled is. This is a very simplified version of my code but if this can be answered ill be able to implement it in my actual code. So basically what i want to do is have two different scrips but when Enabled changes to true or false i want it to also change the other script. Please answer the question if possible without the solution being put it all in one script.

Assets/Standard Assets & Mine/My Scripts/snipershooting.cs(23,58): error CS0176: Static member `BackMenuScript.Enabled' cannot be accessed with an instance reference, qualify it with a type name instead i think if we fix this error things could never be better. i think this is the problem causing the other one.

This is the single most-asked (and most-answered) question on this site... there's also a page dedicated to the subject in the [manual][1] and on the [UnityGems][2] site. Please search before asking. [1]: http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html [2]: http://unitygems.com/script-interaction1/

2 Answers

2

First you have to access script1 in script2

script2 
---------------------

Script1 script1Object;

void Start()
{
script1Object = GetComponent<Script1>();
}

void Example()
{
if(!script1Object.Enabled) {
debug.log ("ESC has been pressed");
}
}

There are several ways to do it. If script 1 will only ever exist on one object, make Enabled static. Then from script 2, you can use “Script1.Enabled”.

Otherwise, you would need a reference to script 1.
I.e. Script1 obj = GetScript1SomeHow();
Then use obj.Enabled

hey i have the error - Assets/Standard Assets & Mine/My Scripts/snipershooting.cs(26,58): error CS0176: Static member `BackMenuScript.Enabled' cannot be accessed with an instance reference, qualify it with a type name instead. i think i accidentally asked for a solution to this error through an answer on this lel.

Static members are accessed via class while instances members are accessed via instance. You are trying to access a static member by an instance, so remove the keyword static or use the class name to access it instead of a variable