Spawning 2 defenders at the same time

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;
    	}
    }

Well i figured it soon after posting this. I noticed my extra Instantiate.

1 Like

I’m having this same problem except I only have Instantiate in my SpawnerDefender code once.

Also they both spawn under the Defender parent.

I hadn’t realised until the later part of the course as it seems to be stopping the detection of enemies and bringing up the “can’t find spawner in lane” Debug error.