When Instatiating a prefab it creates two copies and i don't know why.

When i run my game for some reason two lines show up in the hierarchy every time i drag my mouse in order to create a line. I have also noticed that occasionally it kinda works as i expect where it only creates two copies the first time and then create a single line every time after the first. Likely i’m just editing the script and some stuff happens and it figures something out… i honestly have no idea. Other than that it looks fine and having two lines doesn’t seem to break anything, but i have a feeling it will in the future so i wanna get it fixed.

i want to stress that the attached image shows the result of me dragging my mouse across the screen once.

public class ToggleInputNode : MonoBehaviour
{
    [SerializeField] GameObject _linePrefab;
    [SerializeField] float _radiusToCreateLine = 1f;


    private bool _lineCreated = false;

    List<GameObject> _lines = new List<GameObject>();

    private void OnMouseDrag()
    {
        //Create a Line if the User drags the mouse a certain range
        if (DistanceFromCenter(_radiusToCreateLine) && !_lineCreated)
        {
            Debug.Log("There are " + _lines.Count + " lines");
            _lines.Add(Instantiate(_linePrefab, transform.position, Quaternion.identity));
            _lineCreated = true;
        }
    }

    private void OnMouseExit()
    {
        _lineCreated = false;
    }

    private bool DistanceFromCenter(float r)
    {
        //Calculate distance between the node and the mouse
        Vector2 nodePos = new Vector2(transform.position.x, transform.position.y);
        Vector2 mousePos = GetMousePosition();
        float distance = Vector2.Distance(nodePos, mousePos);

        if (distance >= r)
            return true;

        return false;
    }

6902291--808067--Capture.PNG

Do you have this script in the scene twice? Precisely when are they being created?

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

You could add Debug.Log(gameobject.name); to find out if you have accidently attached the script twice somewhere in your scene (as Kurt-Decker stated).

Also you could add a log to OnMouseExit() because for some reason it seems to trigger when it shouldn’t. That way you can narrow down the problem.

1 Like