- Home /
How to share a variable through multiple copys of the same script
Hello! I've been working on a top down shooter game lately and I've run into an issue. So I'm thinking the door (blue rectangle) can only be opened when the two buttons who share the same button script are activated. In the button script, I have a public int variable (named activationNumber for referencing) to record the number of times the button has been pressed. I'm hoping by pressing each of the two buttons once (so activationNumber would be two), the door would open. However, the door can only reference one of the buttons, and can only record one of the buttons' activationNumber. I'm wondering how to create a shared variable to accomplish what I envisioned. Thank you!
Answer by tonialatalo · Aug 29, 2020 at 10:07 PM
Why do you think the door can refer only to a single button?
You can simply put two button references to the door and then check them both.
Alternatively, you can make the button script so that they have both individual and shared data - here is that in code in replit so you can execute it too .. that's not in Unity but it works the same way there:
using System;
class MainClass {
public static void Main (string[] args) {
var b1 = new Button();
var b2 = new Button();
Console.WriteLine(Button.ButtonsPressed);
b1.Press();
Console.WriteLine(Button.ButtonsPressed);
b2.Press();
Console.WriteLine(Button.ButtonsPressed);
}
}
class Button {
private bool ThisPressed = false;
public static int ButtonsPressed = 0;
public bool Press()
{
if (!ThisPressed) {
ThisPressed = true;
ButtonsPressed += 1;
return true;
}
return false;
}
}
Output:
0
1
2
You can try the code there: https://repl.it/@ToniAlatalo/RoundAdolescentSection (press run)
Thank you so much! What you said makes a lot of sense. Both solutions should do the trick.
Answer by logicandchaos · Aug 30, 2020 at 03:00 PM
Just make the variable static and then it will be shared among all instances of that class. That's exactly what static variables are for. You could also use a scriptable object to share values. But if they use the same script just make the variable static.
Thank you so much! Static variables are exactly what I needed!
Your answer
Follow this Question
Related Questions
Apply the same script on multiple objects 1 Answer
2D raycast shooting in the wrong direction 1 Answer
I am having problems with making my character face the movement direction after stopping. 1 Answer
Jump functionality for a 2D Top Down game? 1 Answer
How to change animation's speed in C#? 2 Answers