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!
Answer by _DS_1 · Dec 03, 2020 at 01:21 AM
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
}
Your answer
Follow this Question
Related Questions
Moving player along a Vector 2D 0 Answers
Operator '==' is ambiguous on operands of type 'Vector2' and 'Vector3' 1 Answer
Pulling the player only towards one of multiple objects 0 Answers
How To Change GameObject Position Base On Screen Size? 1 Answer
I want an enemy to move around the room like a bishop, aka. diagonally. 0 Answers