Raycasting is one of the most frequently used functions in Unity game development. Raycasting draws a line into space from an origin point until it hits something. It can be used not only to cast literal rays like for ray guns, but also it can be used to check for things being near each other such as determining if you’re standing on the ground or if a character can see something.
A basic shooting script
- Make a basic FPS character controller scene with an FPS Controller prefab and a cube to stand on. You can download the FPS Controller prefab quickly from here.
- Create a C# script called Shooter.cs with the following:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Raycaster : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { Debug.Log("bang!"); RaycastHit hit; if (Physics.Raycast( Camera.main.transform.position, Camera.main.transform.forward, out hit, 1000f )) { hit.collider.SendMessage("RayTargetHit", SendMessageOptions.DontRequireReceiver); } } } }
- You can attach the script to a game object childed to the main camera object inside the Character Controller Prefab.
- When you click the mouse, it will fire a ray until it hits something and send a message to any scripts on that target object with a public function named “RayTargetHit”.
- Create another script called RaycasterTarget.cs:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RaycasterTarget : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame public void RayTargetHit () { Debug.Log("Target hit"); } }
- Test it out by placing a cube in the world with RaycasterTaget.cs.
- Try playing the game and shoot at the target. You should see “Bang!” and “Target hit” in the console confirming it worked.
- Modify the script to do something more interesting!
Unity Let’s Try: Shooting with Raycasts tutorial
Unity has an excellent tutorial about shooting with raycasts.
Beyond Let’s Try Shooting With Raycasts: Ice and heat rays with particle and ice effects
You can try an enhanced version of the raycast tutorail which adds switchable laser, ice and heat rays that build up ice on targets that slow them down and heat that melts the ice. It adds cool particle effects and uses the same shooting scripts for the player and the enemies.