It's critical that you
do not use static variables
in this case.
You'll be pleased to know the solution is simple. Have a script called AttachToDoor
public void AttachToDoor()
{
private bool isOpen;
public float doorSpeed;
etc etc
public void OpenCloseDoor()
{
your code to open/close a door
}
}
Drag AttachToDoor
on to your door. Notice OpenCloseDoor()
is marked public
.
Next have ANOTHER, SEPARATE script, AttachToButton
public void AttachToButton()
{
public AttachToDoor amazaingDoorScript;
etc etc
void Update()
{
if (Input.GetButton("Fire1"))
if (DoPlayerLookAtButton() && isAnimationReadyToPlay)
amazaingDoorScript.OpenCloseDoor();
}
}
Drag an AttachToButton
on to any of your "buttons".
Look at the Inspector, and notice the slot "amazaingDoorScript".
Literally drag the door, to that slot, and it will connect the AttachToDoor to the "amazaingDoorScript" variable.
But note ... you can do this to as many buttons as you want.
Any time you make a button, just put an AttachToButton
on the button.
You could even have another script which, just as an example, opens and closes the door randomly:
public AttachToDoor amazaingDoorScript; ...
Invoke("test",Random.Range(5f,10f)); ...
private void test()
{
// have a ghost mess with the door occasionally
amazaingDoorScript.OpenCloseDoor();
Invoke("test",Random.Range(5f,10f));
}
This is a really basic concept in Unity, and once you can do this you can do anything. Enjoy!
Take the opportunity, to learn how to use UnityEvent.
If you're learning Unity, this is a good opportunity to learn about UnityEvent
. Using UnityEvent is really the heart of everyday Unity engineering.
Here is a excellent tutorial: https://stackoverflow.com/a/36249404/294884
On the BUTTON, do this
public void AttachToButton()
{
public UnityEvent buttonClicked;
void Update()
{
if (Input.GetButton("Fire1"))
if (DoPlayerLookAtButton() && isAimationReadyToPlay)
{
Debug.Log("Button pressed!");
if (buttonClicked!=null) buttonClicked.Invoke();
}
}
}
Hit save. Run the game, and notice that when a button is pressed in the game, you will see the Log "Button pressed!".
Now, look in the editor, at your buttons.
Notice that actually in the editor, you have added an amazing drag and drop area at the bottom of your AttachToButton
.
Now stop the game, and try this. Look at one of your buttons. Look at the drag and drop area for the event buttonClicked
. In fact, drag your door ON TO that ... and select the routine OpenCloseDoor
.
Run the game and watch what happens. Voilà! Amazing right?