Hello. I have been trying to make a script that switches between pistol models in-game. The idea is, you can press 1 on your keyboard to have the pistol model be swapped out with another one, grabbed from the child of a game object called “PistolPickups”. I’ve gotten a basic script so far, but I have no idea how to actually make the script interact with objects in game.
What I want the script to do is, upon pressing the ‘1’ key on your keyboard, replace the “Pistol05” child with “Pistol01”, from the “PistolPickups” gameobject. I could not find any method of interacting with the game in such way. Any help would be appreciated.
Here is the unfinished code.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class weaponSwitching : MonoBehaviour {
public bool kb_OnePressed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey ("1"))
kb_OnePressed = true;
if (kb_OnePressed) {
}
}
}
void Update () {
if (Input.GetKey ("1"))
kb_OnePressed = true;
if (kb_OnePressed) {
}
}
Why dont you just put the code that will go into the if(kb_OnePressed) into the Input.GetKey, you are simply adding extra steps are more room for error.
Also, when handling switching weapons I started with Instantiating them at a position and rotation relative to the camera. However, this gave me a couple of issues. I then switched it so that all the guns are in the scene in the position I like and parented to the camera. In code I would then simply turn the gun on when a button was pressed and turn the currently equipped weapon off.
The way that I did it:
This is my code and would need tweaking to match what you want.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
int equipped;
void Start ()
{
equipped = 0;
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.Alpha1))
{
EquipWeapon(0);
}
else if(Input.GetKeyDown(KeyCode.Alpha2))
{
EquipWeapon(1);
}
else if(Input.GetKeyDown(KeyCode.Alpha3))
{
EquipWeapon(2);
}
else if(Input.GetKeyDown(KeyCode.Alpha4))
{
EquipWeapon(3);
}
}
void EquipWeapon(int toEquip)
{
if(GameManager.Instance.playersGuns.Count > toEquip)
{
if(equipped != toEquip)
{
GameManager.Instance.playersGuns[equipped].SetActive(false);
GameManager.Instance.playersGuns[toEquip].SetActive(true);
GameManager.Instance.equippedGun = GameManager.Instance.playersGuns[toEquip];
}
else
{
Debug.Log("I will not allow you to equip an already equipped gun!");
}
equipped = toEquip;
}
else
{
Debug.Log("No Weapon in this slot!");
}
}
}
The list of guns is on my GameManager script but you can put this in the script above:
public List<GameObject> playersGuns;
Make sure that the script also has: (It is required to create lists)
using System.Collections.Generic;
Simply add your guns to the list in the inspector.