Two Defenders Spawn at once

I select (for example) Lizard button, I click a square - Lizard appears and looks normal, but there are two Lizards as can be seen in the Hierarchy. It seems to be affecting the defenders ability to detect attackers.

There was another poster with this issue a year or two ago, he solved his own problem when he realised he had two lots of instantiate in one script.

I have the same problem but I only have instantiate once.

I’m using Unity 2017

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DefenderSpawner : MonoBehaviour {

    public Camera myCamera;

    private GameObject parent;


    // Use this for initialization
    void Start()
    {
        parent = GameObject.Find("Defenders");

        if (!parent)
      {
          parent = new GameObject("Defenders");

       }

    }

  

     void OnMouseUp()
    {
        Vector2 rawPos = CalculateWorldPointOfMouseClick();
        Vector2 roundedPos = SnapToGrid(rawPos);
        GameObject defender = Button.selectedDefender;
        Quaternion zeroRotation = Quaternion.identity;
        GameObject newDefender = Instantiate(defender, roundedPos, zeroRotation) as GameObject;

        newDefender.transform.parent = parent.transform;

    }

    Vector2 SnapToGrid (Vector2 rawWorldPos) {
        float newX = Mathf.RoundToInt(rawWorldPos.x);
        float newY = Mathf.RoundToInt(rawWorldPos.y);

        return new Vector2(newX, newY);
    }

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

}

Hi,

Please add the following line to OnMouseUp:

Debug.Log(GetInstanceID() + ": Instantiated Defender.");

How many times does this message appear when you click the mouse button once, and what instance id do you see?

Hi Nina

I get two debug logs, one starts with -4668:, the other starts with -4652:

Two instance ids indicate that there are two DefenderSpawner instances in your scene. One needs to be removed. Check all game objects in your Hierarchy.


See also:

Oh, that was the problem.

/thanks Nina

I’m glad I was able to help. :slight_smile:


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms