Running Script on current prefab only (not all intances)

This is just my first time messing around with instantiation and prefabs, and I’ve hit a problem I’m not sure how to solve.

The following script lives on a prefab which is used many times in my scene (a chunk of street). The goal is to instantiate another prefab (a crosswalk) on the street when clicked. When I run the game to test this, however, clicking any street spawns a crosswalk on every street chunk in the scene. I only want to instantiate on the chunk clicked. How should I approach this?

var prefab : GameObject; 

function Update () {

// Write some quick and dirty script for placing a crosswalk.
if(Input.GetMouseButtonDown(2))
Instantiate(prefab,transform.position, transform.rotation);
Debug.Log("Player Clicked on a Street Segment");
}

The problem is, you are doing nothing to determine which section of street you want to instantiate a crosswalk on! The code as it stands will execute on every street in the scene as soon as you press the mouse (which, of course, you already know).

The easiest way to manage this would be to shoot a raycast from the position of the mouse, and find out which one it hit. A quick modification to your script will do this.

First, make sure you have a collider on your street segment.

if(Input.GetMouseButtonDown(2))
    if(collider.Raycast(Camera.main.ScreenPointToRay (Input.mousePosition)))
    {
        Instantiate(prefab,transform.position, transform.rotation);
        Debug.Log("Player Clicked on a Street Segment");
    }
}

Of course, this will have to calculate as many raycasts as there are roads- which could get a bit inefficient after a while. Instead, you should put the raycast on a single manager script, and then just put a common tag ‘CreateCrosswalk’ on all the road segments-

if(Input.GetMouseButtonDown(2))
    var hit : RaycastHit;
    if(Physics.Raycast(Camera.main.ScreenPointToRay (Input.mousePosition), hit))
    {
        var hitTrans : Transform = hit.transform;
        if(hitTrans.gameObject.tag == "CreateCrosswalk")
        {
            Instantiate(prefab, hitTrans.position, hitTrans.rotation);
            Debug.Log("Player Clicked on a Street Segment");
        }
    }
}

Then, you will only do one raycast per click!

Instead of using the update method with a check for the mouse button being held down, use the OnMouseDown() method. Make sure your object has a collider.

It uses raycasting under the hood, but it prevents code obfuscation.