Hello people :slight_smile:

I’d like to change the color of a sprite in a scene when you look at it.

I checked if theraycast hits anything and it does (the sprites have colliders on them), it all works, but now I that I want to change the color Unity always gives me those “… is not a member of …” errors :frowning:

Here’s the code:

#pragma strict
var rend = GetComponent.<Renderer>();
function Start () {

}

function Update () {
	var hit : RaycastHit;
	var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5,0));
    Debug.DrawRay(transform.position, Vector3(Screen.width*0.5, Screen.height*0.5,0) * 100, Color.green);
    
		if(Physics.Raycast(ray, hit, 100)){
			Debug.Log("Look, there's something!");
			hit.collider.GameObject.rend.material.SetColor ("_Color", Color.red);
			}
}

Help pls! Thanks :slight_smile:

So what do I do if I only want the object to have another color while the ray is hitting it?

Try changing:

hit.collider.GameObject.rend.material.SetColor ("_Color", Color.red);

to:

hit.transform.gameObject.GetComponent.<Renderer>().material.color = Color.red;

To have the sprite only change colour while looking at it, you just need to change it back when the ray doesn’t hit it. In the snippet below I’m assuming you’ve tagged all your sprites with the tag “LookSprite”. This is an easy way to identify what you’ve hit with your Raycast. Choose a tag that you like and substitute it for “LookSprite”. See here for more on Tags. We can use two scripts to achieve the desired behaviour. The first is attached to all the sprites and makes sure that they change back to their original colour when not hit by the ray.

Colour.js

#pragma strict

public var change : boolean;

function Start()
{
	change = false;
}

function Update()
{
	if (change == false)
	{
		GetComponent.<Renderer>().material.color = Color.black;
	}
}

function LateUpdate()
{
	if (change == true)
	{
		GetComponent.<Renderer>().material.color = Color.red;
		change = false;
	}
}

The sprite will change colour in the same frame that the boolean “change” is set to true. Now the second script uses a Raycast to set the boolean on the object it hits.

ChangeColour.js

 #pragma strict

 function Update ()
 {
     var hit : RaycastHit;
     var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5,0));
     Debug.DrawRay(transform.position, Vector3(Screen.width*0.5, Screen.height*0.5,0) * 100, Color.green);
     
    if(Physics.Raycast(ray, hit, 100))
    {
        Debug.Log("Look, there's something!");
        if (hit.transform.tag == "LookSprite")
        {
            //You hit a sprite
            hit.transform.gameObject.GetComponent.<Colour>().change = true;
        }
 }