so when playing in the game view I click in a defender. One defender spawns under the “Defender” parent as it should and another one is spawned at the same time, but outside by itself in the hierarchy.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Glitch Garden
public class SpawnerDefender : MonoBehaviour {
public Camera myCamera;
private GameObject defenderParent;
void Start ()
{
defenderParent = GameObject.Find ("Defenders");
if (!defenderParent)
{
defenderParent = new GameObject("Defenders");
}
}
// Update is called once per frame
void Update ()
{
}
void OnMouseDown()
{
Vector2 rawPos = CalculateWorldPointOfMouseClick ();
Vector2 roundedPos = SnapToGrid (rawPos);
GameObject defender = Button.selectedDefender;
Quaternion zeroRot= Quaternion.identity;
Instantiate(defender, roundedPos, Quaternion.identity);
GameObject newDefender = Instantiate (defender, roundedPos, zeroRot) as GameObject;
newDefender.transform.parent = defenderParent.transform;
}
//rounds world Vector2 cordinates "rawWorldPos" usable numbers
Vector2 SnapToGrid (Vector2 rawWorldPos)
{
float roundedX = Mathf.RoundToInt (rawWorldPos.x);
float roundedY = Mathf.RoundToInt (rawWorldPos.y);
return new Vector2 (roundedX, roundedY);
}
Vector2 CalculateWorldPointOfMouseClick()
{
float mouseX = Input.mousePosition.x;
float mouseY = Input.mousePosition.y;
float distanceFromCamera = 10f;
Vector3 weirdTriplet = new Vector3 (mouseX, mouseY, distanceFromCamera);
Vector2 worldPos = myCamera.ScreenToWorldPoint (weirdTriplet);
return worldPos;
}
}