Reputation: 491
I have written a code to change the color of a object by selecting it
void Update () {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,out hit, 1000.0f) && Input.GetMouseButtonDown (0))
{
if(hit.collider.gameObject == this.gameObject)
{
Debug.Log("Wall Clicked");
mgr.clickedWall=gameObject;
}
else if(Physics.Raycast(ray,out hit, 1000.0f) && Input.GetMouseButtonDown (1))
{
hit.collider.gameObject.renderer.material.color = Color.red;
}
}
it works fine when main camera is on the initial position but when the camera position changes color changes but not on the object that I clicked.what is the isuue over here.
Upvotes: 0
Views: 214
Reputation: 2167
I feel like your whole logic is wrong. Thy out something like this. please note that this is attached to the camera and not the gameobject you are clicking. I think your problem stems from doing the raycast in a if that also checks if a mouse button is down.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.tag == "Test")
{
Debug.Log("Wall Clcked");
}
}
}
if (Input.GetMouseButtonDown(1))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
hit.collider.gameObject.GetComponent<Renderer>().material.color = Color.red;
}
}
}
Upvotes: 1