Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Scripting' started by nk23a, Mar 15, 2023.

  1. nk23a

    nk23a

    Joined:
    Nov 17, 2019
    Posts:
    3
    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:

    Code (CSharp):
    1. void OnMouseUp()
    2. {
    3.     // toggle ShopUI
    4.     if (!shopUI.gameObject.activeSelf && IsTowerEmpty())
    5.     {
    6.         currentTurretPosition = transform.position;
    7.         Debug.Log(currentTurretPosition);
    8.         shopUI.gameObject.SetActive(true);
    9.     }
    10. }
    11.  
    Code (CSharp):
    1. private void BuyTower(int cost, int towerType, Vector3 position)
    2. {
    3.     if (GameManager.instance.coin >= cost)
    4.     {
    5.         Debug.Log(position);
    6.         tower = Instantiate(towerPrefab[towerType], position, Quaternion.identity);
    7.         GameManager.instance.coin -= cost;
    8.     }
    9. }
    Can anyone help me figure out what’s going wrong? Thanks in advance!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    I don't see where in the code above you call BuyTower()...
     
    Terraya likes this.
  3. nk23a

    nk23a

    Joined:
    Nov 17, 2019
    Posts:
    3
    Sorry that I didn't provide all the code
    here
    Code (CSharp):
    1.     void Start()
    2.     {
    3.         normalTowerButton.onClick.AddListener(() => BuyTower(100, 0, currentTurretPosition));
    4.         laserTowerButton.onClick.AddListener(() => BuyTower(200, 1, currentTurretPosition));
    5.         missileTowerButton.onClick.AddListener(() => BuyTower(300, 2, currentTurretPosition));
    6.     }
     
  4. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    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.
     
    Kurt-Dekker and nk23a like this.
  5. nk23a

    nk23a

    Joined:
    Nov 17, 2019
    Posts:
    3
    That fixed my issue thank you