I have a problem with my shop system, it keeps spawning same object (pistol instead of assault rifle for example) on two of my weapons (buttons which buy the weapon)
Btw, i will fix the minus money problem later because i didn’t have much time.
i also don’t know what is causing this problem that the same object is spawning no matter what button
also sorry for my spaghetti code, im gonna fix it later.
(im using unity 4.6, it’s not the problem with the old unity version but instead my crappy coding skills)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Serialization;
public class Shop : MonoBehaviour {
[System.Serializable]
public struct Item
{
public string Name;
public int Price;
public GameObject itemToSpawn;
}
// Use this for initialization
public GameObject CE;
public CanvasGroup CG;
public GameObject Player;
public Transform ItemSpawn;
public GameObject buttonPrefab;
public List<Item> Items = new List<Item>();
void Start () {
foreach(Item item in Items)
{
GameObject button = (GameObject)Instantiate(buttonPrefab);
button.transform.parent = CE.transform;
Button buttonCom = button.GetComponent<UnityEngine.UI.Button>();
buttonCom.GetComponentInChildren<Text>().text = item.Name;
buttonCom.onClick.AddListener(() => Buy(item));
}
}
// Update is called once per frame
void Update () {
if (Vector3.Distance(Player.transform.position, transform.position) <= 5 && Input.GetKeyDown(KeyCode.E))
{
CG.alpha = 1;
CG.interactable = true;
CG.blocksRaycasts = true;
Screen.lockCursor = false;
Screen.showCursor = true;
}
}
public void Quit ()
{
CG.alpha = 0;
CG.interactable = false;
CG.blocksRaycasts = false;
Screen.lockCursor = true;
Screen.showCursor = false;
}
public void Buy(Item iem)
{
if(Items.Contains(iem))
{
Subtract(iem.Price);
CreateItem(ItemSpawn, iem.itemToSpawn);
}
}
private void Subtract(int money)
{
Player.GetComponent<Score>().RemoveMoney(money);
}
private void CreateItem(Transform position, GameObject item)
{
Instantiate(item, position.transform.position, Quaternion.identity);
}
}