Search Unity

Changing the Color of an object during runtime using ray casts

Discussion in 'Scripting' started by SHIMMY, May 16, 2013.

  1. SHIMMY

    SHIMMY

    Joined:
    Dec 28, 2012
    Posts:
    107
    Just want it so that when the ray cast hits the cube (with a red material) it turns to blue. I am successfully using the ray cast, but getting no result with change colour.
    Code (csharp):
    1. //Raycast against tiles
    2.     var fwd = transform.TransformDirection(Vector3.forward);
    3.     var hit : RaycastHit;  
    4.    if(Physics.Raycast(transform.position, fwd, hit, 10))
    5.    {
    6.       Debug.Log("Hit");
    7.         if(hit.trigger.gameObject.name == "Red")
    8.         {
    9.          print ("Hit Red Box");
    10.         renderer.material.color = Color.blue; //Obviously didn't work
    11.         }  
    12.    }
    13.    
    14.    Debug.DrawRay(transform.position, fwd * 10, Color.green);
    15.    
    16. }  
    Thanks, guys.
     
  2. ar0nax

    ar0nax

    Joined:
    May 26, 2011
    Posts:
    485
    Try this one, because you were not trying to change the color on the object you hit, but on the object you were raycasting from.
    Code (csharp):
    1. hit.collider.renderer.material.color = Color.red;
     
  3. SHIMMY

    SHIMMY

    Joined:
    Dec 28, 2012
    Posts:
    107
    Whenever i get a collision the console comes up saying:
    "MissingFieldException: Field 'UnityEngine.RaycastHit.trigger' not found."