- Home /
Help. Newbie trying to have more than one button powered door a scene
As it says, I'm trying to have multiple doors a scene. The button and the door work like how I want them to but every time I bring in a new door, all the buttons in the hierarchy no matter their location ties it self to the most recently loaded door script (which is always the final door).
Button Script:
public class ButtonController : MonoBehaviour
{
public int buttonValue;
public ButtonDoors gameDoor;
public Sprite buttonUnTouched;
public Sprite buttonTouched;
private SpriteRenderer buttonSpriteRenderer;
// Start is called before the first frame update
void Start()
{
gameDoor = FindObjectOfType<ButtonDoors> ();
buttonSpriteRenderer = GetComponent<SpriteRenderer> ();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Boxes")
{
gameDoor.DoorOpens (buttonValue);
buttonSpriteRenderer.sprite = buttonTouched;
}
}
void OnTriggerExit2D (Collider2D other)
{
if (other.tag == "Boxes")
{
gameDoor.DoorOpens (-buttonValue);
buttonSpriteRenderer.sprite = buttonUnTouched;
}
}
}
Door Script:
public class ButtonDoors : MonoBehaviour
{
public Sprite doorClosed;
public Sprite doorOpen;
private SpriteRenderer doorSpriteRenderer;
public Collider2D DoorPass;
public int allButtons;
// Start is called before the first frame update
void Start()
{
doorSpriteRenderer = GetComponent<SpriteRenderer> ();
}
// Update is called once per frame
void Update()
{
}
public void DoorOpens (int allButtonsPressed)
{
allButtons += allButtonsPressed;
if (allButtonsPressed == 3)
{
DoorPass.enabled = false;
doorSpriteRenderer.sprite = doorOpen;
}
else
{
DoorPass.enabled = true;
doorSpriteRenderer.sprite = doorClosed;
}
}
}
I'd imagine this might be an easy fix but I'm not seeing it myself. I did sorta find two solutions but one of them just has the door calling for the button script instead, causing the exact same issue but now with the buttons. The other talks about sending the information through an observer class but that was more for a zelda like puzzle dungeon crawler using keys to open doors where as I'm trying to make a 2D puzzle platformer using buttons on the ground to open doors. Thanks in advance for any help you can give!
Answer by Zoedingl · Jun 22, 2020 at 10:53 AM
The reason for this is that you are using the GetComponet method. If you want every door to work with it's own buttons, you must make the gameDoor public and in the Unity inspector assign the right door.
Hope this helped.
Yeah, that fixed it. I thought that line of code was required to call things from another script. I guess it's more for convenience when you're making universal things. Thanks for the help!