Complex Interactions with Objects

Using Raycasts to highlight an object (enemy) when in view and reset when not

You don’t have access to this lesson
Please register or sign in to access the course content.
Length: 10 minutes
Click the image to load an interactive demo.

Make sure you have a player object that you can move.

Create an object to be detected and assign a tag to it. In this example the tag is Enemy.

Create a detection script and attach it to the player.

Complete Highlighting Script

Below is the complete script which is attached to the player to handle detecting an object with the tag “Enemy” in front of it and changing its colour to red.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayCastEnemySeen : MonoBehaviour
{
    private bool Key;
     public Camera camera;
    public Color highlightedColor;
    GameObject enemy;

    void RayCastChangeColorOnHit() {
        RaycastHit hit;
        //Ray forwardRay = new Ray (transform.position, transform.forward);
        Ray forwardRay = camera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
 
        if (Physics.Raycast (forwardRay, out hit, 50.0f)) {
            if(hit.transform.gameObject.CompareTag("Enemy")) {
                //hit.collider.GetComponentInParent<PlayerMovementFPS_MLAPI>().TakeDamage(50);
                if(enemy == null) {
                    Debug.Log("I hit a player for the first time");
                    enemy = hit.transform.gameObject;
                    //highlightedColor = new Color(hit.transform.GetComponent<Renderer>().material.color.r, hit.transform.GetComponent<Renderer>().material.color.g, hit.transform.GetComponent<Renderer>().material.color.b);
                    highlightedColor = hit.transform.GetComponent<Renderer>().material.color;
                    Debug.Log(highlightedColor.ToString());
                    hit.transform.GetComponent<Renderer>().material.SetColor("_Color", Color.red);
                    Debug.Log(highlightedColor.ToString());
                    Key = true;
                }
            } else {
                if(enemy != null) {
                     enemy.GetComponent<Renderer>().material.SetColor("_Color", highlightedColor);
                     enemy = null;
                 }
                    Debug.Log("Not hitting enemy");
                     // Hitting something else.
                     Key = false;
            
            }
        } else if (Key == true)
             {
                 // not anymore.
                 if(enemy != null) {
                     enemy.GetComponent<Renderer>().material.SetColor("_Color", highlightedColor);
                     enemy = null;
                 }
                 Debug.Log("Lost enemy");
                 Key = false;
             }
    }

    // Update is called once per frame
    void Update()
    {

        RayCastChangeColorOnHit();
        
    }
}