Help Need: Trouble with BuyTower() function in tower defense game - Vector3 position issue

I’m having trouble with the BuyTower() function in my tower defense game. The currentTurretPosition shows the correct Vector3 value, but when I call the BuyTower method and print the position value using Debug.Log, it shows the vector (0,0,0) instead of the expected value.

Here’s my code:

void OnMouseUp()
{
    // toggle ShopUI
    if (!shopUI.gameObject.activeSelf && IsTowerEmpty())
    {
        currentTurretPosition = transform.position;
        Debug.Log(currentTurretPosition);
        shopUI.gameObject.SetActive(true);
    }
}
private void BuyTower(int cost, int towerType, Vector3 position)
{
    if (GameManager.instance.coin >= cost)
    {
        Debug.Log(position);
        tower = Instantiate(towerPrefab[towerType], position, Quaternion.identity);
        GameManager.instance.coin -= cost;
    }
}

Can anyone help me figure out what’s going wrong? Thanks in advance!

I don’t see where in the code above you call BuyTower()…

1 Like

Sorry that I didn’t provide all the code
here

    void Start()
    {
        normalTowerButton.onClick.AddListener(() => BuyTower(100, 0, currentTurretPosition));
        laserTowerButton.onClick.AddListener(() => BuyTower(200, 1, currentTurretPosition));
        missileTowerButton.onClick.AddListener(() => BuyTower(300, 2, currentTurretPosition));
    }

you have added your method on start event, “currentTurretPosition” is a value type it will make a copy of the value you passing in that start frame, it’s mean your currentTurretPosition wont get update on other frame.

what you can do is, create a new class call “TurrentData” with “currentTurretPosition” in it. and then you can pass that in as reference type.

2 Likes

That fixed my issue thank you