The question is answered, right answer was accepted
Change the dropping prefab for each in-game drop
I am writing a inventory script, and in the Items script (the items that the enemies drop on the ground), I need something that could swap prefabs, 'cause on my Inventory Script I have a variable public GameObject dropPrefab;
, and I need to swich it to the correct prefab once I drop my items on the ground. This script down here is the Item script (the one that must control the itemPrefab that is at the inventory script):
using UnityEngine; using System.Collections;
public enum ItemType {MANA, HEALTH, HPPotion, MPPotion, FOOD, DRINK}; public enum Quality {COMMON, UNCOMMON, RARE, EPIC, LEGENDARY, DEVELOPER, ARTIFACT};
public class Item : MonoBehaviour { public ItemType type; public Quality quality;
public Sprite spriteNeutral;
public Sprite spriteHighlighted;
public int maxSize;
public float strength, intellect, agility, stamina;
public string itemName;
public string description;
[SerializeField]private bool ChecIfCanRotate=false;
void Update ()
{
if (ChecIfCanRotate) {transform.Rotate(0,50*Time.deltaTime,0);}
}
public void Use ()
{
switch (type)
{
case ItemType.MANA:
if (PlayerCS.ManaVal < 100) {PlayerCS.isUnderEcto = true;}
break;
case ItemType.HEALTH:
if (PlayerCS.LifeVal < 100) {PlayerCS.isUnderSoul = true;}
break;
case ItemType.HPPotion:
if (PlayerCS.LifeVal < 96) {PlayerCS.isUnderSoulJar = true;}
break;
case ItemType.MPPotion:
if (PlayerCS.ManaVal < 96) {PlayerCS.isUnderEctoJar = true;}
break;
case ItemType.FOOD:
if (PlayerCS.HungerVal < 96) {PlayerCS.isEating = true;}
break;
case ItemType.DRINK:
if (PlayerCS.HungerVal < 91) {PlayerCS.isDrinking = true;}
break;
}
}
public string GetTooltip ()
{
string stats = string.Empty;
string color = string.Empty;
string newLine = string.Empty;
if (description != string.Empty)
{
newLine = "\n";
}
switch (quality)
{
case Quality.COMMON:
color = "white";
break;
case Quality.UNCOMMON:
color = "green";
break;
case Quality.RARE:
color = "navy";
break;
case Quality.EPIC:
color = "magenta";
break;
case Quality.LEGENDARY:
color = "orange";
break;
case Quality.ARTIFACT:
color = "red";
break;
case Quality.DEVELOPER:
color = "purple";
break;
}
if (strength > 0)
{
stats += "\n+" + strength.ToString() + " Strength";
}
if (intellect > 0)
{
stats += "\n+" + intellect.ToString() + " Intellect";
}
if (agility > 0)
{
stats += "\n+" + agility.ToString() + " Agility";
}
if (stamina > 0)
{
stats += "\n+" + stamina.ToString() + " Stamina";
}
return string.Format("<color=" + color + "><size=16>{0}</size></color><size=14><i><color=lime>"+newLine+"{1}</color></i>{2}</size>", itemName, description, stats);
}
void OnCollisionEnter (Collision collision)
{
if (collision.gameObject.tag == "Player") {Destroy(gameObject);}
}
public void SetStats (Item item)
{
this.type = item.type;
this.quality = item.quality;
this.spriteNeutral = item.spriteNeutral;
this.spriteHighlighted = item.spriteHighlighted;
this.maxSize = item.maxSize;
this.itemName = item.itemName;
this.description = item.description;
this.intellect = item.intellect;
this.strength = item.strength;
this.stamina = item.stamina;
this.agility = item.agility;
switch (type) {
case ItemType.MANA:
/*Here I need something that could change the GameObject that I set in
the Inventory script as the Drop Prefab to the correct item prefab.*/
break;
case ItemType.HEALTH:
/*Here I need something that could change the GameObject that I set in
the Inventory script as the Drop Prefab to the correct item prefab.*/
break;
case ItemType.MPPotion:
/*Here I need something that could change the GameObject that I set in
the Inventory script as the Drop Prefab to the correct item prefab.*/
break;
case ItemType.HPPotion:
/*Here I need something that could change the GameObject that I set in
the Inventory script as the Drop Prefab to the correct item prefab.*/
break;
}
}
}
And this is the Inventory script:
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; using System;
public class Inventory : MonoBehaviour { #region Floats private float inventoryWidth, inventoryHight; private float hoverYOffset;
public float slotPaddingLeft, slotPaddingTop;
public float slotSize;
private float savingTime;
#endregion
#region Ints
public int slots;
public int rows;
private static int emptySlots;
private int splitAmount;
private int maxStackCount;
#endregion
#region Canvas
private RectTransform inventoryRect;
private static Slot from, to;
private static Slot movingSlot;
private static Inventory instance;
private static CanvasGroup canvasGroup;
public Canvas canvas;
public EventSystem eventSystem;
public Text stackText;
private static Text sizeText;
public Text sizeTextObject;
private static Text visualText;
public Text visualTextObject;
#endregion
#region Booleans
private static bool inventoryLock;
private bool InvOnOffCheck;
#endregion
#region GameObjects
[SerializeField]private GameObject iconPrefab;
private static GameObject hoverObject;
private static GameObject clicked;
public GameObject slotPrefab;
public GameObject selectStackSize;
private static GameObject selectStackSizeStatic;
public GameObject mana;
public GameObject health;
public GameObject ectoplasmPot;
public GameObject soulPot;
public GameObject tooltipObject;
private static GameObject tooltip;
public GameObject dropItem;
private static GameObject playerRef;
#endregion
#region Collections
private List<GameObject> allSlots;
#endregion
#region Properties
public static int EmptySlots
{
get {return emptySlots;}
set {emptySlots = value;}
}
public static CanvasGroup CanvasGroup
{
get {return Inventory.canvasGroup;}
}
public static Inventory Instance
{
get
{
if (instance == null)
{
instance = GameObject.FindObjectOfType<Inventory>();
}
return Inventory.instance;
}
}
public static bool InventoryLock
{
get {return Inventory.inventoryLock;}
}
#endregion
void Start ()
{
tooltip = tooltipObject;
visualText = visualTextObject;
sizeText = sizeTextObject;
selectStackSizeStatic = selectStackSize;
playerRef = GameObject.Find("Player");
canvasGroup = transform.parent.GetComponent<CanvasGroup>();
if (canvasGroup.alpha == 0) {InvOnOffCheck = false;}
else if (canvasGroup.alpha == 1) {InvOnOffCheck = true;}
CreateLayout();
LoadInventory();
movingSlot = GameObject.Find("MovingSlot").GetComponent<Slot>();
}
void Update ()
{
savingTime += 1*Time.deltaTime;
if (savingTime >= 300) {SaveInventory(); savingTime = 0;}
if (eventSystem.IsPointerOverGameObject(-1) && InvOnOffCheck == true || !movingSlot.IsEmpty) {PlayerCS.canShoot = false;}
else if (!eventSystem.IsPointerOverGameObject(-1) && movingSlot.IsEmpty && InvOnOffCheck == true || InvOnOffCheck == false) {PlayerCS.canShoot = true;}
if (Input.GetMouseButtonUp(0))
{
if (!eventSystem.IsPointerOverGameObject(-1) && from != null)
{
from.GetComponent<Image>().color = Color.white;
foreach (Item item in from.Items)
{
float angle = UnityEngine.Random.Range(0.0f, Mathf.PI * 2);
Vector3 v = new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle));
v *= 2;
GameObject.Instantiate(dropItem, v, Quaternion.identity);
}
from.ClearSlot();
Destroy(GameObject.Find("Hover"));
to = null;
from = null;
emptySlots++;
}
}
else if (!eventSystem.IsPointerOverGameObject(-1) && !movingSlot.IsEmpty)
{
foreach (Item item in movingSlot.Items)
{
float angle = UnityEngine.Random.Range(0.0f, Mathf.PI * 2);
Vector3 v = new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle));
v *= 2;
GameObject tmpDrp = (GameObject)GameObject.Instantiate(dropItem, playerRef.transform.position - v, Quaternion.identity);
}
PlayerCS.canShoot = false;
movingSlot.ClearSlot();
Destroy(GameObject.Find("Hover"));
}
if (hoverObject != null)
{
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out position);
position.Set(position.x, position.y - hoverYOffset);
hoverObject.transform.position = canvas.transform.TransformPoint(position);
}
if (Input.GetKeyDown(KeyCode.RightShift)) {inventoryLock = !inventoryLock;}
if (Input.GetKeyDown(KeyCode.I))
{
if (canvasGroup.alpha == 1)
{
canvasGroup.alpha = 0;
InvOnOffCheck = false;
PutItemBack();
}
else
{
canvasGroup.alpha = 1;
InvOnOffCheck = true;
}
}
if (Input.GetKey(KeyCode.LeftControl) && inventoryLock == true)
{
if (eventSystem.IsPointerOverGameObject(-1))
{
MoveInventory();
PlayerCS.canShoot = false;
}
}
else if (Input.GetKeyUp(KeyCode.LeftControl)) {PlayerCS.canShoot = true;}
}
public void ShowToolTip (GameObject slot)
{
Slot tmpSlot = slot.GetComponent<Slot>();
if (!tmpSlot.IsEmpty && hoverObject == null && !selectStackSizeStatic.activeSelf)
{
visualText.text = tmpSlot.CurrentItem.GetTooltip();
sizeText.text = visualText.text;
tooltip.SetActive(true);
float xPos = slot.transform.position.x + slotPaddingLeft;
float yPos = slot.transform.position.y - slot.GetComponent<RectTransform>().sizeDelta.y - slotPaddingTop;
tooltip.transform.position = new Vector2(xPos, yPos);
}
}
public void HideToolTip ()
{
tooltip.SetActive(false);
}
public void SaveInventory ()
{
string content = string.Empty;
for (int i = 0; i < allSlots.Count; i++)
{
Slot tmp = allSlots[i].GetComponent<Slot>();
if (!tmp.IsEmpty)
{
content += i + "-" + tmp.CurrentItem.type.ToString() + "-" + tmp.Items.Count.ToString() + ";";
}
}
PlayerPrefs.SetString("content", content);
PlayerPrefs.SetInt("slots", slots);
PlayerPrefs.SetInt("rows", rows);
PlayerPrefs.SetFloat("slotPaddingLeft", slotPaddingLeft);
PlayerPrefs.SetFloat("slotPaddingTop", slotPaddingTop);
PlayerPrefs.SetFloat("slotSize", slotSize);
PlayerPrefs.SetFloat("xPos", inventoryRect.position.x);
PlayerPrefs.SetFloat("yPos", inventoryRect.position.y);
PlayerPrefs.Save();
}
public void LoadInventory ()
{
string content = PlayerPrefs.GetString("content");
slots = PlayerPrefs.GetInt("slots");
rows = PlayerPrefs.GetInt("rows");
slotPaddingLeft = PlayerPrefs.GetFloat("slotPaddingLeft");
slotPaddingTop = PlayerPrefs.GetFloat("slotPaddingTop");
slotSize = PlayerPrefs.GetFloat("slotSize");
inventoryRect.position = new Vector3(PlayerPrefs.GetFloat("xPos"), PlayerPrefs.GetFloat("yPos"), inventoryRect.position.z);
CreateLayout();
string[] splitContent = content.Split(';');
for (int x = 0; x < splitContent.Length - 1; x++)
{
string[] splitValues = splitContent[x].Split('-');
int index = Int32.Parse(splitValues[0]);
ItemType type = (ItemType)Enum.Parse(typeof(ItemType), splitValues[1]);
int amount = Int32.Parse(splitValues[2]);
for (int i = 0; i < amount; i++)
{
switch (type)
{
case ItemType.MANA:
allSlots[index].GetComponent<Slot>().AddItem(mana.GetComponent<Item>());
break;
case ItemType.HEALTH:
allSlots[index].GetComponent<Slot>().AddItem(health.GetComponent<Item>());
break;
case ItemType.MPPotion:
allSlots[index].GetComponent<Slot>().AddItem(ectoplasmPot.GetComponent<Item>());
break;
case ItemType.HPPotion:
allSlots[index].GetComponent<Slot>().AddItem(soulPot.GetComponent<Item>());
break;
/ case ItemType.FOOD: allSlots[index].GetComponent().AddItem(food.GetComponent()); break; case ItemType.DRINK: allSlots[index].GetComponent().AddItem(drink.GetComponent()); break; / } } } }
private void CreateLayout ()
{
if (allSlots != null)
{
foreach (GameObject go in allSlots)
{
Destroy(go);
}
}
allSlots = new List<GameObject>();
hoverYOffset = slotSize*0.05f;
emptySlots = slots;
inventoryWidth = (slots/rows) * (slotSize + slotPaddingLeft) + slotPaddingLeft;
inventoryHight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;
inventoryRect = GetComponent<RectTransform>();
inventoryRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,inventoryWidth);
inventoryRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,inventoryHight);
int columns = slots/rows;
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "Slot";
newSlot.transform.SetParent(this.transform.parent);
slotRect.localPosition = inventoryRect.localPosition + new Vector3(slotPaddingLeft * (x + 1) + (slotSize * x), -slotPaddingTop * (y + 1) - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize * canvas.scaleFactor);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize * canvas.scaleFactor);
newSlot.transform.SetParent (this.transform);
allSlots.Add(newSlot);
}
}
}
public bool AddItem (Item item)
{
if (item.maxSize == 1)
{
PlaceEmpty(item);
return true;
}
else
{
foreach (GameObject slot in allSlots)
{
Slot tmp = slot.GetComponent<Slot>();
if (!tmp.IsEmpty)
{
if (tmp.CurrentItem.type == item.type && tmp.IsAvailable)
{
if (!movingSlot.IsEmpty && clicked.GetComponent<Slot>() == tmp.GetComponent<Slot>())
{
continue;
}
else
{
tmp.AddItem(item);
return true;
}
}
}
}
if (emptySlots > 0)
{
PlaceEmpty(item);
}
}
return false;
}
private void MoveInventory ()
{
Vector2 mousePos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, new Vector3(Input.mousePosition.x - (inventoryRect.sizeDelta.x/2 * canvas.scaleFactor), Input.mousePosition.y + (inventoryRect.sizeDelta.y/2 * canvas.scaleFactor)), canvas.worldCamera, out mousePos);
transform.position = canvas.transform.TransformPoint(mousePos);
}
private bool PlaceEmpty (Item item)
{
if (emptySlots > 0)
{
foreach (GameObject slot in allSlots)
{
Slot tmp = slot.GetComponent<Slot>();
if (tmp.IsEmpty)
{
tmp.AddItem(item);
emptySlots--;
return true;
}
}
}
return false;
}
public void MoveItem (GameObject clicked)
{
Inventory.clicked = clicked;
if (!movingSlot.IsEmpty)
{
Slot tmp = clicked.GetComponent<Slot>();
if (tmp.IsEmpty)
{
tmp.AddItems(movingSlot.Items);
movingSlot.Items.Clear();
Destroy(GameObject.Find("Hover"));
}
else if (!tmp.IsEmpty && movingSlot.CurrentItem.type == tmp.CurrentItem.type && tmp.IsAvailable)
{
MergeStacks(movingSlot, tmp);
}
}
else if (from == null && canvasGroup.alpha >= 1 && !Input.GetKey(KeyCode.LeftShift))
{
if (!clicked.GetComponent<Slot>().IsEmpty)
{
from = clicked.GetComponent<Slot>();
from.GetComponent<Image>().color = Color.gray;
CreateHoverIcon();
}
}
else if (to == null && !Input.GetKey(KeyCode.LeftShift))
{
to = clicked.GetComponent<Slot>();
Destroy(GameObject.Find("Hover"));
}
if (to != null && from != null)
{
if (!to.IsEmpty && from.CurrentItem.type == to.CurrentItem.type && to.IsAvailable)
{
MergeStacks(from, to);
}
else
{
Stack<Item> tmpTo = new Stack<Item>(to.Items);
to.AddItems(from.Items);
if (tmpTo.Count == 0)
{
from.ClearSlot();
}
else
{
from.AddItems(tmpTo);
}
}
from.GetComponent<Image>().color = Color.white;
to = null;
from = null;
Destroy(GameObject.Find("Hover"));
}
}
private void CreateHoverIcon ()
{
hoverObject = (GameObject)Instantiate(iconPrefab);
hoverObject.GetComponent<Image>().sprite = clicked.GetComponent<Image>().sprite;
hoverObject.name = "Hover";
RectTransform hoverTransform = hoverObject.GetComponent<RectTransform>();
RectTransform clickedtransform = clicked.GetComponent<RectTransform>();
hoverTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, clickedtransform.sizeDelta.x);
hoverTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, clickedtransform.sizeDelta.y);
hoverObject.transform.SetParent(GameObject.Find("Canvas").transform, true);
hoverObject.transform.localScale = clicked.gameObject.transform.localScale;
hoverObject.transform.GetChild(0).GetComponent<Text>().text = movingSlot.Items.Count > 1 ? movingSlot.Items.Count.ToString() : string.Empty;
}
private void PutItemBack ()
{
if (from != null)
{
Destroy(GameObject.Find("Hover"));
from.GetComponent<Image>().color = Color.white;
from = null;
}
else if (!movingSlot.IsEmpty)
{
Destroy(GameObject.Find("Hover"));
foreach (Item item in movingSlot.Items)
{
clicked.GetComponent<Slot>().AddItem(item);
}
movingSlot.ClearSlot();
}
selectStackSize.SetActive(false);
}
public void SetStackInfo (int maxStackCount)
{
selectStackSize.SetActive(true);
tooltip.SetActive(false);
splitAmount = 0;
this.maxStackCount = maxStackCount;
stackText.text = splitAmount.ToString();
}
public void SplitStack ()
{
selectStackSize.SetActive(false);
if (splitAmount == maxStackCount)
{
MoveItem(clicked);
}
else if (splitAmount > 0)
{
movingSlot.Items = clicked.GetComponent<Slot>().RemoveItems(splitAmount);
CreateHoverIcon();
}
}
public void ChangeStackText (int i)
{
splitAmount += i;
if (splitAmount < 0) {splitAmount = 0;}
if (splitAmount > maxStackCount) {splitAmount = maxStackCount;}
stackText.text = splitAmount.ToString();
}
public void MergeStacks (Slot source, Slot destination)
{
int max = destination.CurrentItem.maxSize - destination.Items.Count;
int count = source.Items.Count < max ? source.Items.Count : max;
for (int i = 0; i < count; i++)
{
destination.AddItem(source.RemoveItem());
hoverObject.transform.GetChild(0).GetComponent<Text>().text = movingSlot.Items.Count.ToString();
}
if (source.Items.Count == 0)
{
source.ClearSlot();
Destroy(GameObject.Find("Hover"));
}
}
}
Hope you guys can help me with this!
Answer by Igor_Vasiak · Nov 30, 2016 at 02:14 PM
I already figured it out. I used a swich of the type ItemType at the Inventory script, instead of doing it by the Items script:
foreach (Item item in from.Items)
{
float angle = UnityEngine.Random.Range(0.0f, Mathf.PI * 2);
Vector3 v = new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle));
v *= 2;
GameObject tmpDrp;
ItemType type = item.type;
switch (type) {
case ItemType.MANA:
tmpDrp = (GameObject)GameObject.Instantiate(mana, playerRef.transform.position - v, Quaternion.identity);
tmpDrp.GetComponent<Item>().SetStats(item);
break;
case ItemType.HEALTH:
tmpDrp = (GameObject)GameObject.Instantiate(health, playerRef.transform.position - v, Quaternion.identity);
tmpDrp.GetComponent<Item>().SetStats(item);
break;
case ItemType.HPPotion:
tmpDrp = (GameObject)GameObject.Instantiate(soulPot, playerRef.transform.position - v, Quaternion.identity);
tmpDrp.GetComponent<Item>().SetStats(item);
break;
case ItemType.MPPotion:
tmpDrp = (GameObject)GameObject.Instantiate(ectoplasmPot, playerRef.transform.position - v, Quaternion.identity);
tmpDrp.GetComponent<Item>().SetStats(item);
break;
}
}
Follow this Question
Related Questions
Zelda-like inventory system 0 Answers
How to select the item inside of my inventory slot? (Followed a tutorial into a rut) 0 Answers
Enum filter for Item system 1 Answer
How to make a Inventory Hotbar 0 Answers
How Can I make items inventory? (HELP) 0 Answers