- Home /
Trouble with getting this code to work. What am I doing wrong?
I am trying to write a code so that when the user presses the 1 key they will equip the weapon for that slot. I just started it so its not really anything special. If I select the bool to be true in the inspector.. it works.. but if I hit the 1 key it doesn't and I just cannot find out what I am doing wrong. I am open to easier ways of doing this aswell.
Here are the scripts I have so far.
using UnityEngine;
using System.Collections;
public class IHaveA9mm : MonoBehaviour {
public bool equipPistol;
public GameObject pistol;
public Transform weaponSlot;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(equipPistol)
{
//instantiate the weapon to the weaponSlot.
GameObject pistolIP = (GameObject)Instantiate(pistol, weaponSlot.position, weaponSlot.rotation);
equipPistol = false;
}
}
}
Now the equip weapon script. When the user presses 1, it should set this scripts bool to true, and instantiate the weapon.
using UnityEngine;
using System.Collections;
public class EquipWeapon : MonoBehaviour {
// Update is called once per frame
void Update ()
{
if(Input.anyKeyDown)
{
print ("YES");
GameObject.Find("Player").GetComponent<IHaveA9mm>().equipPistol = true;
}
}
}
Answer by deltamish · Apr 16, 2013 at 06:30 AM
Hi there is an easier method to do this
Note I dont recommend using numbers while naming a script(IHaveA9mm) so rename it to something like this (Pistol) using UnityEngine; using System.Collections;
public class EquipWeapon : MonoBehaviour {
public GameObject Weapon_Pistol;
// Update is called once per frame
void Start(){
Weapon_Pistol.SetActiveRecursively(false);
}
void Update ()
{
if(Input.GetKeyDown("1"))///try using (Input.GetKeyDown("1")) cause some time (Input.anyKeyDown) doesnt work
{
print ("YES");
Weapon_Pistol.SetActiveRecursively(true);//enables the weapon
Weapon_Pistol.GetComponenet<Pistol>().equipPistol = true;
}
}
}
your Pistol script
using UnityEngine;
using System.Collections;
public class Pistol : MonoBehaviour {
public bool equipPistol;
void Update ()
{
if(equipPistol)
{
if(Input.GetButton("Fire1")){
//your fire code
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613100417im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
Creating a Loadout 1 Answer