- Home /
Check bool from multiple instances of the same script
Hello, I am trying to check if a bool on a script is false if it leaves the collider. The "dropzones" objects all have the tag "dropzone" and the script "DropZone1" is in the scene multiple times, attached once to each of the dropzone objects. In their Start Function, I have written satisfied as false. My boundary script looks like this:
public class DestroyByBoundary : MonoBehaviour
{
GameObject[] dropzones;
DropZone1 dropzonescript;
GameController gameController;
private void Start()
{
gameController = FindObjectOfType<GameController>();
dropzones = GameObject.FindGameObjectsWithTag("dropzone");
foreach (GameObject zones in dropzones)
{
DropZone1 dropzonescript = zones.GetComponent<DropZone1>();
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "dropzone")
{
verifyifSatisfied(dropzonescript.satisfied);
}
}
void verifyifSatisfied(bool satisfied)
{
if (dropzonescript.satisfied == false)
{
gameController.NoAnswer();
gameController.DecideIfDisplay();
}
}
}
I would like to make it so if one of those "dropzones" leaves the collider, it calls that "verifyifsatisfied" function. However, whenever I test, the code has a nullreferenceexception. Is there a way to fix this?
What were you trying to achieve with that foreach? Your current code loops through all dropzones and keeps overwriting the one dropzonescript reference, which means that dropzonescript always points to the last dropzone in the loop (and only that one).
I see you closed the question, but I'll post this here in case you're interested.
Try something along the lines of this:
public class DestroyByBoundary : $$anonymous$$onoBehaviour
{
GameObject[] dropzones;
//DropZone1 dropzonescript; // Ady: Delete this
GameController gameController;
private void Start()
{
gameController = FindObjectOfType<GameController>();
dropzones = GameObject.FindGameObjectsWithTag("dropzone");
foreach (GameObject zones in dropzones)
{
// Ady: I have no idea what you were trying to do here
//DropZone1 dropzonescript = zones.GetComponent<DropZone1>(); // Ady disabled code
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "dropzone")
{
// Ady: Gets the DropZone1 script that's attached to the object that exited the trigger
var dropzonescript = GetComponent<DropZone1>(); // Ady
verifyifSatisfied(dropzonescript); // Ady
}
}
void verifyifSatisfied(DropZone1 dropzonescript) // Ady: Replaced parameter with DropZone1 type
{
if (dropzonescript.satisfied == false)
{
gameController.NoAnswer();
gameController.DecideIfDisplay();
}
}
}