- Home /
instantiate gameobjects inside a canvas
Hello everyone. I have been struggling for few days (!) now with something that I assume is pretty easy to solve. I tried alot of different approaches to this and failed misrely (I'm new so please bear with me).
This is the situation: I have a pretty simple Inventory system in my project. It works like this: The player can pick up items (he has a "Pick up" script for that. the item can be dropped by click on an X button above each inventory slot. and they the items can be picked up again. The inventory contains three scripts in total: Inventory script, Pick Up script and Drop Item script.
My problem is: When my player pick an item, it does show inside the inventory, but its position changes depending on the player position. meaning, if my player is higher on the map inside my scene, the item will spawn inside the inventory higher than if the player is at a lower position at the map.
Please - Help me :)
there are my scripts:
public class Inventory : MonoBehaviour { public bool[] isFull; public GameObject[] slots; }
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PickUp : MonoBehaviour { private Inventory inventory; public GameObject itemButton;
private void Start()
{
//checks if the player collides with this pickup indicating its time to add it to the inventory
inventory = GameObject.Find("Player").GetComponent<Inventory>();
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
for (int i = 0; i < inventory.slots.Length; i++)
{
if (inventory.isFull[i] == false)
{
inventory.isFull[i] = true;
Instantiate(itemButton, inventory.slots[i].transform, false);
Destroy(gameObject);
break;
}
}
}
}
}
slots script: (this is where my item instantiate inside the canvas): using System.Collections; using System.Collections.Generic; using UnityEngine;
public class slot : MonoBehaviour { private Inventory inventory; public int i; private void Start() { inventory = GameObject.Find("Player").GetComponent(); }
private void Update()
{
if (transform.childCount <= 0)
{
inventory.isFull[i] = false;
}
}
public void DropItem()
{
foreach (Transform child in transform)
{
child.GetComponent<dropItem>().SpawnDroppedItem();
GameObject.Destroy(child.gameObject);
}
}
}