Script not changing a public variable of another's game object script

This is a simple script of a game object that colides with something:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColisaoNoPe : MonoBehaviour
{
    public GameObject alvo;

    // Start is called before the first frame update
    private void Start()
    {

    }

    // Update is called once per frame
    private void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        print("ColisaoNoPe collision with " + other);
        if (other.gameObject.CompareTag("piso"))
        {
            alvo.GetComponent<MovLinear>().piso = true;
            print("ColisaoNoPe piso -> true");
        }
        //alvo.GetComponent<MovLinear>().ColisaoNoPe(other, true);
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        //if (other.gameObject.CompareTag("piso")) alvo.GetComponent<MovLinear>().piso = false;
        //alvo.GetComponent<MovLinear>().ColisaoNoPe(other, false);
    }
}

The script ‘MovLinear’ in ‘alvo’ has the boolean variable ‘piso’ declared as public and set to false in the Start function. There is a print in a fixed update to see the ‘piso’ state, the result is always false.

I also tried to make a public function that changes a private variable, however what happens is the ‘piso’ variable only changes inside the scope of the function, so will remains unchanged for the rest of the script. It seems a new bool piso is auto-created inside a function, this is bizarre to me, though I am not understanding how the scope of variables works in C#…

// attach this script to object in hierarchy (example: FirstObject)
public class FirstScript : Monobehaviour {
public bool myBool = true;
}

// attach this script to object in hierarchy
public class SecondScript : Monobehaviour {

    public FirstScript firstScript; // add in this field object with script FirstObject

    public void Change() {
        firstScript.myBool = false;
    }
}

@gustavopinent
You can refer piso by using FindObjectOfType object

FindObjectOfType<Class_name_in_which_variable_is_declared>().piso = true;

Hope this helps :slight_smile: