I am working on a 2D platformer game, similar to Mario. In this game, I have made a switch and switch block. There are two states on and off. On-switch blocks are red, and Off-switch blocks are blue. The state of the switch affects which block is active. The problem is when I add more than one switch. The blocks will only listen to one switch, so I want the switches to be in sync. So no matter where you are on the map the blocks will remain consistent. To link the switch blocks I used a foreach statement, but now the only switch that works is the first in the array.
Here is the code:
On Off Blocks:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnOffBlock : MonoBehaviour
{
public SwitchBlock SwitchCheck;
public BlockType block;
private SpriteRenderer rend;
private BoxCollider2D coll;
[SerializeField]
private Sprite[] SwitchSkin;
// Start is called before the first frame update
void Start()
{
rend = GetComponent<SpriteRenderer>();
coll = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
if (block == BlockType.RedOn && SwitchCheck.IsOn)
{
rend.sprite = SwitchSkin[0];
coll.enabled = true;
}
else if (block == BlockType.BlueOff && !SwitchCheck.IsOn)
{
rend.sprite = SwitchSkin[2];
coll.enabled = true;
}
else if (block == BlockType.RedOn && !SwitchCheck.IsOn)
{
rend.sprite = SwitchSkin[1];
coll.enabled = false;
}
else if (block == BlockType.BlueOff && SwitchCheck.IsOn)
{
rend.sprite = SwitchSkin[3];
coll.enabled = false;
}
else
{
rend.sprite = SwitchSkin[0];
coll.enabled = true;
}
}
}
The Switches:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwitchBlock : MonoBehaviour
{
public GameObject[] allBlocks;
public SwitchState state;
public bool IsOn = false;
private SpriteRenderer rend;
[SerializeField]
private Sprite[] SwitchSkin;
void Start()
{
rend = GetComponent<SpriteRenderer>();
allBlocks = GameObject.FindGameObjectsWithTag("switch");
}
void Update()
{
SwitcherOoh();
}
private void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.tag == "Head")
{
if (state == SwitchState.on)
{
state = SwitchState.off;
}
else if (state == SwitchState.off)
{
state = SwitchState.on;
}
}
}
private void SwitcherOoh()
{
if (state == SwitchState.on)
{
foreach (GameObject block in allBlocks)
{
block.GetComponent<SwitchBlock>().state = state;
}
rend.sprite = SwitchSkin[0];
IsOn = true;
}
else if (state == SwitchState.off)
{
foreach (GameObject block in allBlocks)
{
block.GetComponent<SwitchBlock>().state = state;
}
rend.sprite = SwitchSkin[1];
IsOn = false;
}
}
}
and the enums (they are in a larger enum class)
public enum BlockType{ RedOn, BlueOff };
public enum SwitchState { on, off };