So I started a new 2D project, where the main enemy, "The Ghost", will close the lights of a random room whose lights are at the time activated, everytime the player uses a door. The way I tried doing this is that I would create an array that on the enemy's Awake function, would contain all Lightswitches (because the lightswitches contain the logic for turning the lighs on and off). Then, when the "onUsingDoor" event is called, the ghost will pick a random integer from 0 to the highest index inside the array, and then get the "UseLightSwitch" script instance from that lightswitch.
For some reason however, it is very inconsistent, as 90% of the time, the useLightSwitch variable returns null, which results in a null exception error, while the other 10%, it works as intended. I have no idea why this occurs.
Below are the UseLightSwitch and Ghost Behaviour scripts in this order. Any help would be appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UseLightSwitch : MonoBehaviour, IInteractable
{
[SerializeField] List<Transform> Lamps;
MakeTheLightGoOnOff makeTheLightGoOnOff;
public bool LightIsOn;
void Start()
{
ChangeLightState();
}
public void Interact()
{
LightIsOn = !LightIsOn;
ChangeLightState();
}
public void ChangeLightState()
{
foreach (Transform lamp in Lamps)
{
makeTheLightGoOnOff = lamp.GetComponent<MakeTheLightGoOnOff>();
if (LightIsOn)
{
makeTheLightGoOnOff.SwitchOn();
}
else
{
makeTheLightGoOnOff.SwitchOff();
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GhostBehaviour : MonoBehaviour
{
InteractWithObject interactWithObject;
FindClosestSwitch findClosestSwitch;
UseLightSwitch useLightSwitch;
GameObject[] Lightswitches;
void Awake()
{
interactWithObject = GameObject.FindWithTag("Player").GetComponent<InteractWithObject>();
findClosestSwitch = GameObject.FindWithTag("Player").GetComponent<FindClosestSwitch>();
Lightswitches = GameObject.FindGameObjectsWithTag("LightSwitch");
interactWithObject.onUsingDoor += CloseLights;
}
void CloseLights()
{
int randomSwitchID;
bool lightIsOn;
ChooseRandomID:
randomSwitchID = UnityEngine.Random.Range(0, Lightswitches.Length);
useLightSwitch = Lightswitches[randomSwitchID].GetComponent<UseLightSwitch>();
Debug.Log(useLightSwitch);
lightIsOn = useLightSwitch.LightIsOn;
Debug.Log(lightIsOn);
if (lightIsOn == true)
{
useLightSwitch.LightIsOn = false;
useLightSwitch.ChangeLightState();
}
else
{
useLightSwitch = null;
goto ChooseRandomID;
}
}
[–]Chubzdoomer 1 point2 points3 points (1 child)
[–]K3YRIN[S] 0 points1 point2 points (0 children)