Placing a gameobject with restrictions

I am newbie in programming and I am making a tower defense game 2d. My problem is I want to make a restriction to place a tower only, if the mother tower is in place or within its range. I'm sorry if my explanation is a bit confusing. For example, you can oly place a certain tower within the range of the mother tower and only if that mother tower is placed. I don't exctly know if I have to create a function for this or create a range game object for the placement attached to the mother tower. Any help and tips would be appreciated, thank you. This is by the way unity C#.

That's simple! All you have to do is, first to find the mother tower by name by going GameObject mother = Find("Mother") or whatever you call it. Check if (mother != null), and if so take the Euclidean distance between the mother's Vector2 and the tower's Vector2 like Vector2.Distance(mother.transform, tower.transform) (assuming you have tower defined as another GameObject for your tower.

All together now:

GameObject mother = Find("Mother");
if (mother != null) {
if (Vector2.Distance(Input.mousePosition, mother.transform.position) < 20) { // replace that with your range
// place your tower on click
} else
print("Too far m8");
} else
print("Build a mother first m8");

• @Kram Yup!! Good luck on your future endeavours :D Aug 4, 2017 at 4:37
• Just don't call GameObject.Find() inside Update(), it's expensive. Aug 4, 2017 at 5:04
• @Draco18s Ahhh yes totally forgot. Call Find() in Start() not Update(). Sorry... I didn't really test this out cuz I was busy Aug 4, 2017 at 5:15
• No worries, Daneolog, I make that comment on a lot of posts, just so that future readers know of the pitfall. Speaking of, do you know how Camera.main works? GameObject.FindObjectWithTag() and it doesn't cache the results. Know what happens when you have a canvas object with no camera set? It uses Camera.main... Aug 4, 2017 at 5:23