I am trying to create a feature where you can drag and drop an icon from your inventory and it will “drop” the item on the floor in the game. This is the function I created for doing that:
public void DropItemOnGround()
{
// Drop the item on the ground (with an offset)
List<int> posOrNeg = new List<int>() { -1, 1 };
float offsetX = Random.Range(0, 0.4f) * posOrNeg[Random.Range(0, posOrNeg.Count)];
float offsetY = Random.Range(0, 0.4f) * posOrNeg[Random.Range(0, posOrNeg.Count)];
Vector2 dropPosition = new Vector2(transform.position.x + offsetX,
transform.position.y + offsetY);
Instantiate(gameController.GetComponent<DropController>().GetPickup("Sword"),
dropPosition, transform.rotation);
}
This item is attached to my player, and the “dropPosition” basically creates a little bit of variation in where the item is dropped relative to the player so the items don’t all stack on each other.
For whatever reason, the item does not drop on the ground and just re-instatiates itself in the menu as an icon. However, if I change my code so that instead of “dropPosition” I just manually create a new Vector2:
public void DropItemOnGround()
{
// Drop the item on the ground (with an offset)
List<int> posOrNeg = new List<int>() { -1, 1 };
float offsetX = Random.Range(0, 0.4f) * posOrNeg[Random.Range(0, posOrNeg.Count)];
float offsetY = Random.Range(0, 0.4f) * posOrNeg[Random.Range(0, posOrNeg.Count)];
Vector2 dropPosition = new Vector2(transform.position.x + offsetX,
transform.position.y + offsetY);
Instantiate(gameController.GetComponent<DropController>().GetPickup("Sword"),
new Vector2(-1.8f, 2.0f), transform.rotation);
}
Now the item drops on the ground as I expected. Obviously, I cannot dynamically change the spot the weapon is dropped without a variable. I don’t understand why this is happening, I’ve also tested printing out exactly what “dropPosition” equals and it does come out as a legitimate, expected Vector2 with expected coordinates. Any ideas? Thank you!