top of page

Selection with Raycast Using Mouse - Unity3D

  • thetperson314
  • Jan 14, 2022
  • 1 min read

The code:


public class RayCastScript : MonoBehaviour
{
    Camera cam;
    public LayerMask mask;

    void Start()
    {
        cam = Camera.main;
    }

    void Update()
    {
        // Draw Ray
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = 100f;
        mousePos = cam.ScreenToWorldPoint(mousePos);
        Debug.DrawRay(transform.position, mousePos - transform.position,             
        Color.blue);

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray,out hit,100,mask))
            {
                Debug.Log(hit.transform.name);
                hit.transform.GetComponent<Renderer>().material.color = 
                Color.red;
            }
        }
    }
}


Recent Posts

See All

FAVORITES

Try playing Core Keeper and learn from it's sound design!

From the sound effect to the music - this is a masterpiece!

WHAT'S NEW?

New game on Steam and a new mobile video asset are soon to be published!!

I AM THINKING ABOUT

AI is on the rise. Being able to use it in the right cases and explaining the task correctly is no easy task but once you finish a full task without writing a line of code - your world will change!

CONTACT ME

Use any social media to contact me. For any question about programing and project I prefer using my Discord server, See you there!

© 2021 by Amit Klein. Nerd Head.

bottom of page