Disabling a script while pressing a key down
i'm currently trying to make my character not being able to move when i hold down the button that is going to make my character block. by doing this i've tried to disable the script. this however does not work.
i'm using components from player, where the player script grabs playermovement script and the blocking script. so i'll show samples from both Player and Block. because i have a suspicion that the PlayerScript is the culprit
Blocking shield script:
public class BlockingShield : MonoBehaviour {
public bool IsBlocking;
PlayerMovement MoveScript; //getting my script with movements of player
public void BlockingStart ()
{
IsBlocking = false;
MoveScript = GetComponent<PlayerMovement> ();
}
public void BlockingUpdate ()
{
if (Input.GetKeyDown (KeyCode.F)) {
IsBlocking = true;
MoveScript.enabled = false; //cancels scripts to hold player still while blocking
Debug.Log ("BLOCKING");
}
else if (Input.GetKeyUp (KeyCode.F))
{
IsBlocking = false;
MoveScript.enabled = true;
}
}
}
and Player Script
public class Player : MonoBehaviour {
PlayerMovement movementScript;
BlockingShield blockingScript;
void Start()
{
blockingScript = GetComponent<BlockingShield> ();
movementScript = GetComponent<PlayerMovement> ();
blockingScript.BlockingStart ();
movementScript.MoveStart ();
}
void Update()
{
blockingScript.BlockingUpdate ();
movementScript.MoveUpdate ();
}
}
Answer by KoenigX3 · Jan 13, 2017 at 01:58 PM
The 'enabled' property will only disable the Update of the component. You can still call functions from that class, and actually you are doing that:
movementScript.MoveUpdate();
This line will call the MoveUpdate() function every time.
You should only call MoveUpdate() when the F button is not pressed. You could check this in the Player script. You can use your code to disable the Update of the MoveScript.
Also, does it really need to be in a separate component? It could be more efficient if there is only one script to handle this, and you don't need to use separate functions to check if the F button is pressed, and you don't need to call the BlockingUpdate() method in an other function.
Answer by arnbry · Jan 13, 2017 at 02:16 PM
the reason why i use it in a different script, is because as far as i know, you don't want the main script, in this case the player, to know about the movement functions, and whatever else stuff it will later have, like graphics, etc. I believe this is to make later updates and configurations less of a pain when the code is a giant ball of mess.. But even so, thanks to you, i found the problem. Can't believe i didnt notice that easy problem... But thank you nonetheless! Currently works as i intended it to.