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?
CodePudding user response:
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>();
}