- Home /
Object will not instantiate properly as a Vector2 stored in a variable, but will when a new Vector2 is created?
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!
Answer by Bunny83 · Jul 31, 2021 at 06:01 PM
For whatever reason, the item does not drop on the ground and just re-instatiates itself in the menu as an icon.
That sounds like you may have some pick up functionality in your game? So you probably instantiate the object within the radius of the player so it picks it up in the moment you dropped it. Though we can not really tell since we don't know literally anything about your game or what game mechanics you have.
Usually you want to drop items "before" the player and not in or around the player. Though if you have a pick up script it's not clear what range this pickup script has. Most games do implement a cooldown on the items which prevent the item from being picked up immediately for exactly this reason.
Your answer
![](https://koobas.hobune.stream/wayback/20220613041038im_/https://answers.unity.com/themes/thub/images/avi.jpg)