Instantiating gameObject A at a vector2 position from another class

Hi all,

Unity / programming newbie here.

I’m making a 2D game, where I’m trying to instantiate gameObject A from GameSession.cs, at the same position where gameObject B was destroyed in Enemy.cs.

gameObject A (i.e. weaponUpgrade) is instantiating at the right point in time, however it is instantiating at 0,0 - the position of the gameobject on the hierarchy has the GameSession.cs attached.


Instantiating gameObject A

public class GameSession : MonoBehaviour
{
    [SerializeField] GameObject weaponUpgrade;
    public bool weaponUpgraded;

private void Start()
{
    weaponUpgraded = false;
}

public void InstantiateWeaponUpgrade()
{
    GameObject newWeapon = Instantiate
        (weaponUpgrade, 
        transform.position, 
        Quaternion.identity) as GameObject;

    weaponUpgraded = true;

public int GetScore()
{
    return currentScore;
}

}

Instantiating gameObject B

private void Die()
{
Destroy(gameObject);

int currentScore = gameSession.GetScore();

if (currentScore >= 1000)
{
    if (gameSession.weaponUpgraded == false)
    {
        gameSession.InstantiateWeaponUpgrade();
    }
}

}

I have since tried (1) creating a public Vector2 variable in the Enemy.cs to try and capture the x,y position at enemy death and (2) passing this Vector2 variable into the GameSession.cs - without any luck.

Any help much appreciated!

Try your method 2, passing the vector2 position into GameSession.InstantiateWeaponUpgrade(Vecto2 position).

 public void InstantiateWeaponUpgrade(Vector2 positionIns)
 {
     GameObject newWeapon = Instantiate
         (weaponUpgrade, 
         positionIns, 
         Quaternion.identity) as GameObject;
     weaponUpgraded = true;
}

And in the Die() method:

private void Die()
{
  
    int currentScore = gameSession.GetScore();
    if (currentScore >= 1000)
    {
        if (gameSession.weaponUpgraded == false)
        {
            gameSession.InstantiateWeaponUpgrade(gameObject.transform.position);
        }
    }
   Destroy(gameObject); // Destroing a gameObject at the end of the method
}