Alternate solution

I decided to implement a public Getter. In PlayerController.cs I implemented the following at the top of the script:

    {
        get { return _canMove; }
    } 

    private bool _canMove = true;

Then where you need to check it, you add a tiny bit of extra code:

        if (other.gameObject.CompareTag("Ground") && FindObjectOfType<PlayerController>().CanMove)
        {
               //Do crash-related stuff here
        }

Having a private bool variable protects against accidentally setting it from outside the PlayerController class, while only having to manage one state and the public Getter let’s me read the bool wherever I want.

Not entirely sure it’s the cleanest/best solution but I did enjoy the challenge of working it out.

Using properties (that’s what it’s called when using a getter and/or setters) is a nice way to expose variables. As a professional software engineer specialized in .NET/C#, I use it all the time. It can be done a bit cleaner like this, but the way you did it is fine as well:

public bool CanMove { get; private set; }

This will behave the same way as your piece of code. The get is public (due to the public in front of bool), but it can only be set within this class, due to the private in front of set.

One tip though: in this case it’s probably better to store the PlayerController in a variable or field. Since you also need it within the if statement to disable to controls, you then only have to retrieve it once. It will also make it slightly easier to read (‘playerController.CanMove’ is easier to read then what you have now) .

1 Like

Privacy & Terms