I used a list to solve the one defender per Square problem
You can also use Physics2D.OverlapPointAll.
When you click on a square it creates a List “Collider2D[ ]” and stores all colliders which touch the grid point (gridPos). If there is no Defender placed, there should only be 1 collider (GameArea-Collider) and the
condition (<2) is met.
Hi both,
Please note, it’s better to copy/paste your code and apply the code fencing characters, rather than using screenshots. Screenshots are ideal for displaying specific details from within a game engine editor or even error messages, but for code, they tend to be less readable, especially on mobile devices which can require extensive zooming and scrolling.
You also prevent those that may offer to help you the ability to copy/paste part of your code back to you with suggestions and/or corrections, meaning that they would need to type a potentially lengthy response. You will often find that people are more likely to respond to your questions if you make it as easy as possible for them to do so.
Hope this helps
See also;
- Forum User Guides : How to apply code formatting within your post
I did the same thing when Rick posed us the challenge, Edison.
Thank you.
I did something similar, it seems to work quite good
Defender[] defenders = FindObjectsOfType<Defender>();
foreach (Defender thisDefender in defenders)
{
if (thisDefender.transform.position == new Vector3(roundedPos.x, roundedPos.y, 0f))
{
Debug.Log("Can't place that here");
return;
}
that typo in defender is triggering me!
My solution is super hacky and ugly, but this is what I came up with.
bool IsThereAnyoneHere()
{
// Check and see if there is another defender on the square.
// FindObjectsByType Defender. Gettransform.
var defenders = FindObjectsOfType<Defender>();
foreach (Defender placedDefender in defenders)
{
var placedDefenderPosition = new Vector2
(placedDefender.transform.position.x,
placedDefender.transform.position.y);
if (placedDefenderPosition == GetSquareClicked())
{
youCanPlaceHim = false;
break;
}
else
{
youCanPlaceHim = true;
}
}
return youCanPlaceHim;
}
private void AttemptToPlaceDefenderAt(Vector2 gridPos)
{
var StarDisplay = FindObjectOfType<StarDisplay>();
int defenderCost = defender.GetStarCost();
if (StarDisplay.HaveEnoughStars(defenderCost) &&
IsThereAnyoneHere())
{
SpawnDefender(gridPos);
StarDisplay.SpendStars(defenderCost);
}
}