- Home /
Trying to change the color of a game object.
I want clicking and/or touching a certain game object on the scene to change the color of another game object. So far I am able to use the mouse and keyboard for this with the script below.
using UnityEngine; using System.Collections;
public class ColorChanger : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButton (1))
{
gameObject.GetComponent<Renderer>().material.color = Color.green;
}
if (Input.GetKeyDown (KeyCode.P))
{
gameObject.GetComponent<Renderer>().material.color = Color.magenta;
}
}
}
But I want to be able to click on another game object to change this. I have searched the Scripting API but have been unable to find something to do this. Any help would be appreciated!
Answer by OctoMan · Jun 24, 2015 at 07:49 AM
I recommend using raycasting to check if you clicked the object, and when you hitted the requested object change the material.
public void Update ()
{
if(Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 100))
{
//here you can react
if(hit.gameObject.tag == "whatever")//if your gameobject with the tag got hit
{
//change the color
}
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Button Modifications 2 Answers
Blend into next color instead of jumping to next color 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Referencing color change when object is 'deselected' 2 Answers