- Home /
This question was
closed Mar 01, 2020 at 04:31 PM by
Nuxytor for the following reason:
The question is answered, right answer was accepted
Question by
Nuxytor · Feb 25, 2020 at 06:03 PM ·
c#spawnproblem during runtimeshop
Need help with my shop system (spawning same weapon no matter what)
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);
}
}
Comment
Best Answer
Answer by Nuxytor · Feb 26, 2020 at 09:20 AM
Nevermind, i rewrote the shop system and it is now working.