Hello.
I need to show and hide object when other object was pressed. But when i try to use bool “pressed” in other script console show: error CS0103: The name `pressed’ does not exist in the current context. How could I fix it?
If that’s a different script, you’ll need a reference to an exisiting instance of the script that’s got the variable.
But you haven’t provided enough information. Please elaborate a little bit more.
There are multiple ways of doing that.
One of the easiest is linking the script instance in the inspector.
In order for this to work, declare a field of the component type you’d like to access in the second script.
Consider this example:
public class Example_01 : MonoBehaviour
{
public void SomeMethod()
{
Debug.Log("Something called me.");
}
}
public class Example_02 : MonoBehaviour
{
// either this
public Example_01 _example01a;
// or this (I recommend to get used to using the SerializeField attribute as early as possible)
[SerializeField]
private Example_01 _example01b;
private void Start()
{
_example01a.SomeMethod();
}
}
You could also get the reference programmatically, but this involves to resolve the GameObject first, on which the other component resides. Afterwards, you’d call any suitable variant of GetComponent to get the reference to the actual component.
Look at the example above.
If you place both classes in their own files and attach both to some gameobjects, you’ll see a slot in the inspector when you click the gameobject that’s got Example_02 attached.
The slot accepts instances of type Example_01, as that’s the type which has been used to declare the field. Now drag and drop the gameobject with Example_01 into the slot. If that doesn’t work, you’ve done something wrong.
Ok, I recommend you start with the tutorial series in the official learn section. You miss some important basics.
Anyway, I’ll try once more with exactly the scripts you provided except that I wrapped it in a class.
Place this in a C# file named Script01
public class Script01 : MonoBehaviour
{
public bool pressed = false;
private void OnMouseDown()
{
pressed = !pressed;
}
}
and this in a C# file named Script02
public class Script02 : MonoBehaviour
{
public Script01 script01;
private void Start()
{
gameObject.SetActive(false);
}
private void Update()
{
if (script01.pressed == true)
{
gameObject.SetActive(true);
}
else if (script01.pressed == false)
{
gameObject.SetActive(false);
}
}
}
Drag the first script onto the object you want to click on.
Drag the second script on the other object.
Now, drag and drop the object that’s got the first script attached into the slot (in the inspector) that you see when you select the second object.
Even if that works, make sure you’ll start with some tutorials that teach you basics. The more you skip, the more problems will arise later. Even if a topic seems irrelevant or boring, spend some minutes with it.