0

This is a really dumb question but I have been trying to reference to the DisableMovement method by creating object, and why the player continue moving after can move is false? (the player touches the ground )

// PlayerController script using UnityEngine;

public class PlayerController : MonoBehaviour
{
    
     bool canMove;
    // Start is called before the first frame update
    void Start()
    {
        canMove = true;
        
    }

    // Update is called once per frame
    void Update()
    {
        if (canMove)
        {
            RotatePlayer();
            BoostUp();
        }
    }

    private void BoostUp()
    {
        
    }

    private void RotatePlayer()
    {
        
    }
    public void DisableMovement()
    {
        canMove = false;
    }
}

// CrashDetector script

using UnityEngine;
using UnityEngine.SceneManagement;

public class CrashDetector : MonoBehaviour
{
    
    PlayerController playerController = new PlayerController();

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
           
            playerController.DisableMovement();
            Invoke("ReloadScene", FinishLine.DelayTime - 3);
        }
    }
    void ReloadScene()
    {

        SceneManager.LoadScene("Level 1");
    }
}

And lastly, What is the purpose of creating OOP object in Unity script? I saw that we could access the script through get component but is there any solution else to access it by creating object or use static keyword? And when to use static keyword?

7
  • Is this question about C# or UnityScript? It looks like the code you've specified is C#, not UnityScript. Commented Jul 20, 2022 at 7:20
  • oh okay let me edit it Commented Jul 20, 2022 at 7:21
  • you are creating new undefined script with 'PlayerController playerController = new PlayerController();' but if you already assigned playerController you should use 'playerobj.GetComponent<PlayerController>().DisableMovement();' to properly access public method. Commented Jul 20, 2022 at 8:20
  • it is still possible to create static class and get access to variables from it, but all this variables should be public, either this class will be useless, then you can get data from this static class like this: yourStaticClass.variable = something; variable = yourStaticClass.variable; Commented Jul 20, 2022 at 8:40
  • 1
    Yeah, i just saw that i wrote the same as just derHugo did, but he made it clearer. Commented Jul 20, 2022 at 9:38

1 Answer 1

2
PlayerController playerController = new PlayerController();

is not allowed and makes no sense.

You do not want to create a new instance of PlayerController - which again is not allowed by Unity anyway: Using new on a MonoBehaviour will print a warning and lead to unexpected behavior!

What you rather want to do is getting a reference to an already existing instance e.g. have a field exposed in he Inspector

public PlayerController playerController;

or

[SerializeField] private PlayerController playerController;

and reference your existing component via drag and drop.

Or altaneratively get in on runtime via e.g.

private PlayerController playerController;

private void Awake()
{
    // if it is attached to the same object
    playerController = GetComponent<PlayerController>();

    // if it is somewhere higher in the hierarchy
    playerController = GetComponentInParent<PlayerController>();

    // if it is somewhere lower in the hierarchy
    playerController = GetComponentInChildren<PlayerController>();

    // if there is only one but anywhere in the scene
    playerController = FindObjectOfType<PlayerController>();
}
Sign up to request clarification or add additional context in comments.

3 Comments

And about the static keyword, when we can use it in unity :>? and if my class isn't inherited from Monobehaiviour, means we can use the new keyword now? , where and when to use the new keyword?
Unity is just c# ... you can use static wherever you want but I wouldn't recommend it ... it is often the "lazy" way of solving dependency issues and might kick you in the back later on. E.g. as soon as you ant to move your app to multiplayer etc statics often cause issues as they apply to everything instead of a single instance as it is intended. You could of course make your bool public static bool canMove; and then simply set PlayerController.canMove = false; from everywhere without needing an instance
And you use new for everything ... except Unity built-in types that require a certain factory method like in this case MonoBehaviour (-> Instantiate / AddComponent / new GameObject("name", typeof(YourComponent))) ... you don't solve anything by making your class not inherit from MonoBehaviour ... because then .. how will it move a certain GameObject?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.