1
\$\begingroup\$

I am very new to unity but not to C#.

I am working in Unity 2D

I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable.

So how do I make a script work only when clicked on that specific prefab

\$\endgroup\$
1
\$\begingroup\$

Add a script to the prefab where you check if the button has been pressed then raycast to get the position of the hit. If this doesnt work, make sure your prefab has a collider component.

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            var clickposition = hit.point;
            // insert code to spawn object at clickposition
        }
    }
}

Note If you'll only perform this action on mousedown or up you can save one check on if (Input.GetMouseButtonDown(0)) every update by implementing the void OnMouseDown() or void OnMouseUp(). This will make your update cleaner as well.

Similar Question: Move object to mouse click position

\$\endgroup\$
  • 2
    \$\begingroup\$ Why not use the built-in OnMouseDown or OnMouseUpAsButton messages? \$\endgroup\$ – DMGregory Aug 23 '17 at 11:45
  • 1
    \$\begingroup\$ True, would be better if only checking mouse actions. Edited the answer \$\endgroup\$ – George Hanna Aug 23 '17 at 13:48
  • \$\begingroup\$ Ok I wrote your code and added it to the road game object and also added a collider (box) but the hit ray cast return is empty. actually I checked on the hit.transform ==null and it was null. Why?? \$\endgroup\$ – AKC Aug 29 '17 at 11:06
  • \$\begingroup\$ Does the box collider cover the entire gameobject? Please update your question or make a new one that includes your current code \$\endgroup\$ – George Hanna Aug 29 '17 at 11:45
  • \$\begingroup\$ Yes, I think it does. I checked on that. I resized the collider. Let me write another question \$\endgroup\$ – AKC Aug 29 '17 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.