Tower Defense- cannot clone the tower
Hi, I played around with Unity a month ago and now I am following the tower-defense tutorial. Those tutorials is a bit advanced to me but I feel more excited to make a real game than work with some basic course. But I stuck at the "placing tower" step.
The github link: The source
The ideal is: When I click the button, I can clone the corresponding tower and place them anywhere on the map.
I have two scripts:
List item
TowerBtn:
using UnityEngine;
public class TowerBtn : MonoBehaviour
{
[SerializeField]
private GameObject towerObject;
public GameObject TowerObject
{
get
{
return towerObject;
}
}
}
It attaches to the button and I use the gameObject prefab (ex : the tower)
List item
And Tower Manager:
using UnityEngine;
using UnityEngine.EventSystems;
public class TowerManager : Singletons<TowerManager>
{
private TowerBtn TowerBtnPressed= null;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 worldpoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldpoint, Vector2.zero);
placeTower(hit);
}
}
public void placeTower(RaycastHit2D hit)
{
Debug.Log(TowerBtnPressed);
if (!GetCurrent().IsPointerOverGameObject() && TowerBtnPressed != null)
{
GameObject newTower = Instantiate(TowerBtnPressed.TowerObject) as GameObject;
newTower.transform.position = hit.transform.position;
}
}
private static EventSystem GetCurrent()
{
return EventSystem.current;
}
public void SelectedTower(TowerBtn towerSelected)
{
TowerBtnPressed = towerSelected;
Debug.Log(TowerBtnPressed);
Debug.Log("Press!" + TowerBtnPressed.TowerObject);
}
}
Every time I press Button, The SelecTower function is called.
The problem: When I click to the map to clone the tower, nothing appears also, no errors. I did some research and found out:
When I click the button, the Debug.Log("Press!" +TowerBtnPressed) show that TowerBtnPressed = towerSelected. But the function placeTower() is useless since the TowerBtnPressed is always null.
When I change [private TowerBtn TowerBtnPressed= null;] to [ public TowerBtn TowerBtnPressed= null;], there are only 1 type of tower is clone( For example I have 3 type of tower-Tower1,tower2,tower3, but only tower1 eventhough I click 3 buttons)
@Cunningham620 : Hi, I found out you are the instructor, could you please help me.
Your answer
Follow this Question
Related Questions
Unity Navigation stopping distance irregularity 1 Answer
moveTowards not working 0 Answers
how to stop spawning wave after game over 1 Answer
Custom waves is an TD game 0 Answers