Daniel Lip
Daniel Lip

Reputation: 11335

How can I use a bool in two scripts to decide if to call a function or not?

At the first script in the FixedUpdate() I'm calling this function :

private void FixedUpdate()
        {
            RotateView();
        }

Inside RotateView :

public void RotateView()
        {
            gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);
        }

And in the second script I'm calling the RotateView like this :

Whilefun.FPEKit.FPEPlayer.Instance.GetComponent<Whilefun.FPEKit.FPEFirstPersonController>().RotateView();

But now I want to add a bool to the script with the RotateView function so I can decide in the second script if to call or not the RotateView in the FixedUpdate.

I want to control if the RotateView will be called or not in the FixedUpdate from the second script or better to control if the line :

gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);

Will be executed or not depending on what flag I set in the second script for example :

Whilefun.FPEKit.FPEPlayer.Instance.GetComponent<Whilefun.FPEKit.FPEFirstPersonController>().RotateView(false);

false so it will not use the line :

gameObject.GetComponent<FPEMouseLook>().LookRotation(transform, m_Camera.transform);

And true will use it. Or false/true if to call the RotateView from inside the FixedUpdate in the first script.

Upvotes: 2

Views: 57

Answers (1)

Philipp Lenssen
Philipp Lenssen

Reputation: 9218

There's many ways to do it:

  • You can assign one script to other via the inspector by using [SerializeField] OtherScript foo;
  • You can have the bool be public and static, then it becomes accessible via OtherScript.foo
  • You can use one of the many ways to grab the other component in the Start() of one of the scripts, e.g. FindObjectByType() or GetComponent<...>() or GetComponentInChildren<...>(), the bool could then be public or public but using a { get; private set; } accessor, or made available via a public function like GetFoo()
  • For super-rare bool checks, like for initial loading settings, there's also the PlayerPrefs class in Unity (but it would usually then be put into another variable)
  • You may even find you're going about the shared bool approach wrong, and instead you want to have one class handle the RotateView call of the other etc.

It all somewhat depends on how you structure your program, what the classes should do, what their scope is and so on.

Upvotes: 2

Related Questions