DefenderSpawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DefenderSpawner : MonoBehaviour
{
Defender defender;
private void OnMouseDown() {
SpawnDefender(GetSquareClicked());
}
public void SetSelectedDefender(Defender defenderToSelect) {
defender = defenderToSelect;
}
private Vector2 GetSquareClicked() {
Vector2 clickPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 worldPos = Camera.main.ScreenToWorldPoint(clickPos);
Vector2 gridPos = SnapToGrid(worldPos);
return gridPos;
}
private Vector2 SnapToGrid(Vector2 rawWorldPos) {
float newX = Mathf.RoundToInt(rawWorldPos.x);
float newY = Mathf.RoundToInt(rawWorldPos.y);
return new Vector2(newX, newY);
}
private void SpawnDefender(Vector2 worldPos) {
Defender newDefender = Instantiate(defender, worldPos, Quaternion.identity) as Defender;
}
}
DefenderButton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DefenderButton : MonoBehaviour
{
[SerializeField] Defender defenderPrefab;
private void OnMouseDown() {
var buttons = FindObjectsOfType<DefenderButton>();
foreach(DefenderButton button in buttons) {
button.GetComponent<SpriteRenderer>().color = new Color32(41, 41, 41, 255);
}
GetComponent<SpriteRenderer>().color = Color.white;
FindObjectOfType<DefenderSpawner>().SetSelectedDefender(defenderPrefab);
}
}
My defenders seem to spawning at random locations
Some help would be wonderful
Thank you