- Home /
gameObject.tag = "player"; breaks code
I'm trying to switch my weapons on my character when the space bar is pressed. I had it before where it would change the prefab but my AI that followed the player then stopped. I changed it up so the player carries both weapons but the second weapon has "BaseballBat.active = false;" on the start method.
This is the code I have
void Update ()
{
if (Input.GetKeyDown ("space"))
{
if (gameObject.tag == "Pitchfork")
{
gameObject.tag = "Player";
Pitchfork.active = false;
BaseballBat.active = true;
}
if (gameObject.tag == "Player")
{
gameObject.tag = "Pitchfork";
BaseballBat.active = false;
PitchTag();
}
}
}
Once the code hits "gameObject.tag = "Player";" it doesn't allow for anymore. It just sits there not even changing the weapon, if I take that line of code out it switches the weapon but there's no going back to the other one.
Answer by Eric5h5 · Nov 22, 2014 at 07:53 PM
If the tag is "Pitchfork", then you set the tag to "Player", and then the next if statement immediately sets it back to "Pitchfork". Use else if, or use switch/case instead.
Also, you should use CompareTag instead of string comparisons. Use KeyCode.Space instead of a string in GetKeyDown. GameObject.active is obsolete; use GameObject.SetActive.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Can a tagged object exclude itself from FindGameObjectWithTag? 3 Answers
I'm trying to adjust tagged objects meshrenderer in C# code. 1 Answer
Get text between two tags C# 1 Answer