- Home /
weapon switch bug
hello every after creating this script i found a bug its when i switch back from key 2 to 1 key 1 one of the weapon donot work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class switchweopen : MonoBehaviour
{
public GameObject shotgun;
public GameObject ak47;
void Start()
{
shotgun.SetActive(false);
}
void Update()
{
if (Input.GetKey(KeyCode.Alpha1))
{
ak47.SetActive(true);
shotgun.SetActive(false);
}
if (Input.GetKey(KeyCode.Alpha2))
{
ak47.SetActive(false);
shotgun.SetActive(true);
}
}
}
Can you define "Do not work"? Like the object is not being set to active correctly?
I was able to recreate a simple project with 3 objects.
ak47 - GameObject (default, nothing added)
shotgun - GameObject (default, nothing added)
controller - GameObject (added script switchweapon)
script is exactly as posted above. When pressing the 1 and 2 key it switches properly. I don't see an error on my end. How do you have your objects setup?
$$anonymous$$ake sure your references are assigned in the controller object or who ever holds the script as seen in this screenshot.
View post on imgur.com
Also quick note, your main class has a typo
public class switchweopen : $$anonymous$$onoBehaviour
should be switchweapon
nop i didnot work but thank anyway for your help
Oh it didn't? You are still having the same issue? Did you take a look at the link I posted to see if your setup is similar? https://imgur.com/nKidguT
Answer by fraubolat · May 27, 2020 at 08:12 PM
Syes i have it the same way and it did not work mabye i should change hte relaod script
Something else may be controlling them. Are there other scripts that perform a SetActive call? Do you have the script attached to multiple objects?
no this is the only script that setactive the objects
Answer by tadadosi · May 28, 2020 at 01:55 PM
Maybe it's because you are using GetKey
that calls your action repeatedly while you are holding the button and your should be using GetKeyDown that acts like a simple button press.
@fraubolat Np! Remember to mark this answer as correct, it'll help other people that could be having the same problem.