- Home /
Checking a bool's state from another script?
Hey everyone, so I'm not too familiar with referencing/interacting with parts of code between scripts, so I don't know if I'm doing this right. I have a ladder that is a collider set as a trigger and a player (with a PlayerController script) that Raycasts to check whether they are within the ladder or not. If they are on the ladder, isClimbing is set to true and they can climb the ladder. At the top of the ladder, I have an empty GameObject called LadderTop which has a platform effector on it, with a LadderTop script attached to it. In the LadderTop script (below), I change the direction the platform effector lets you travel through it whether you are climbing up or down (up arrow or down arrow). I need to check in this script whether isClimbing is true or not because if not, the platform effector will rotate whenever I hit the up or down arrow even if I'm not in the ladder's collider. With this script though, I get the error "NullReferenceException: Object reference not set to an instance of an object LadderTop.Update () (at Assets/__Scripts/LadderTop.cs:19)" at each of the lines where I try to reference isClimbing. Also, in the PlayerController script, isClimbing is a public bool. Any help is appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LadderTop : MonoBehaviour {
private MegaManController playerController;
private PlatformEffector2D ladderTop;
void Start () {
ladderTop = GetComponent<PlatformEffector2D>();
playerController = GetComponent<MegaManController>();
}
void Update () {
if (Input.GetKey(KeyCode.DownArrow) && playerController.isClimbing == true)
{
ladderTop.rotationalOffset = 180;
}
if (Input.GetKey(KeyCode.UpArrow) && playerController.isClimbing == true)
{
ladderTop.rotationalOffset = 0;
}
}
}
Answer by WarmedxMints · Mar 24, 2019 at 04:47 PM
It sounds like the MagaManController class is not attached to the same gameobject as the LadderTop class. GetComponent looks for objects on the same gameObject. GetComponentInChlidren looks for an object on the gameObject and its children. FindObjectOfType looks for objects in the hierarchy
It sounds like you should be using FindObjectOfType
using UnityEngine;
public class LadderTop : MonoBehaviour
{
private MegaManController playerController;
private PlatformEffector2D ladderTop;
private void Start()
{
ladderTop = GetComponent<PlatformEffector2D>();
playerController = FindObjectOfType<MegaManController>();
}
private void Update()
{
if (!playerController.isClimbing)
return;
if (Input.GetKey(KeyCode.DownArrow))
{
ladderTop.rotationalOffset = 180;
}
if (Input.GetKey(KeyCode.UpArrow))
{
ladderTop.rotationalOffset = 0;
}
}
}
Thanks! It works fine with no errors now, appreciate it! Have a good one.
Your welcome. Can you mark the question as answered please so others know the issue has been solved.