enabling and disabling components script not working
Hi, Im new to c# and coding in general and I've made myself a script to effectively switch between two different types of movement (walking and flying), but it wasn't working as I could only switch to flying and not back so I edited it and now none work... I'm sure I'm missing something obvious or because I'm not very good at scripting at all :(
using UnityEngine;
using System.Collections;
public class EnableScripts : MonoBehaviour {
private bool flymode;
private bool walkmode
void Update () {
if (Input.GetKeyDown ("f"))
GetComponent<Move> ().enabled = true;
GetComponent<SpeedUp> ().enabled = true;
GetComponent<WalkScript> ().enabled = false;
flymode = true;
{
if (Input.GetKeyDown ("f") && flymode == true)
GetComponent<Move> ().enabled = false;
GetComponent<SpeedUp> ().enabled = false;
GetComponent<WalkScript> ().enabled = true
flymode = false;
}
}
}
If that's not working (don't know why it isn't), you could set your bools up there as "static" and inside of those functions you want messed with set up an if statement that checks that bool before doing the stuff inside of your move/fly functions.
Thanks, I'll keep this in $$anonymous$$d for future reference.
Answer by corn · Jan 21, 2016 at 10:57 PM
Your code is quite messy, there are typos, and you didn't use brackets to delimit the if blocks, so there isn't much to change. However, always use GetComponent in Start or Awake, never in Update. You only need to get references to these scripts once, not every frame.
using UnityEngine;
using System.Collections;
public class EnableScripts : MonoBehaviour
{
// Start in walk mode
bool flymode = false;
Move move;
SpeedUp speedUp;
WalkScript walk;
void Awake()
{
// Get all references to your other components here
move = GetComponent<Move>();
speedUp = GetComponent<SpeedUp>();
walk = GetComponent<WalkScript>();
}
void Update ()
{
// If player hits f...
if (Input.GetKeyDown("f"))
{
// ... while they're walking, then start flying
if (!flymode)
{
move.enabled = true;
speedUp.enabled = true;
walk.enabled = false;
flymode = true;
}
// Else start walking again
else
{
move.enabled = false;
speedUp.enabled = false;
walk.enabled = true;
flymode = false;
}
}
}
}
Wow! Thank you so much! I really need to learn how to make my codes "cleaner" so thank you again and I'll be looking into this when I get time :D
Your answer
Follow this Question
Related Questions
Dodgeroll script crashing game 0 Answers
Disable a script when its not hit by raycast. still uses 17 to 20% in profiler 0 Answers
Need help making a stamina bar. 0 Answers
Underwater Effect Help 1 Answer
Errors With Game Over Script 1 Answer