Wednesday, February 19, 2020

tower defense - What is grid in Unity and how can I implement it?



I'm a beginner. I need to place a grid on my map in Unity and would like to access it to place a simple object on mouse click. How can I achieve this ?


I am unable to understand the grid functionality, should I have to write code for a 2D array or is there something in Unity that I can access, and what is basically the grid like something when I click my background image ?



Answer



This could be achieved in many ways. Unity has a pretty advanced positioning system as it is.


For just regular positioning look here https://docs.unity3d.com/Manual/PositioningGameObjects.html


But without prior knowledge of whether you are looking to do this in code, it's hard to give a good answer. Try asking more specific, precise questions that you feel others could benefit from that can't be found out with a little bit of research


EDIT: ADDITION This shows how to place a tower, the towers positions are checked against in an arraylist is C#. Hopefully this should give you an idea of how to start.


public GameObject tower;
public GameObject tower2;
private ArrayList towerList = new ArrayList();

void Start()
{
Vector3 towerPosition = new Vector3(1.0F, .75F, 1.0F);
foreach (GameObject towerObject in towerList)
{
if (towerObject.transform.position == towerPosition)
{
// there is already a tower in that position
return;
}

}

tower = (GameObject)Instantiate(tower, new Vector3(1.0F, .75F, 1.0F), this.transform.rotation);
towerList.Add(tower);

// for proof of concept you we're going to try to place the tower
// in the same position as the other one
Vector3 towerPosition2 = new Vector3(1.0F, .75F, 1.0F);
foreach (GameObject towerObject in towerList)
{

if (towerObject.transform.position == towerPosition2)
{
// there is already a tower in that position
return;
}
}
tower2 = (GameObject)Instantiate(tower2, new Vector3(1.0F, .75F, 1.0F), this.transform.rotation);
towerList.Add(tower2);
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...