I’m making a crude tic tac toe game. Basically what i would like to do is just have a person right click or left click on one of nine cubes and it would change color depending on the click. Problem is when a cube is clicked, all 9 cubes change color. This is the code I’m using, basically taken straight from the first scripting tutorial.
using UnityEngine;
using System.Collections;
public class Cubes : MonoBehaviour
{
void Update ()
{
if (Input.GetMouseButtonDown (0))
{
gameObject.renderer.material.color = Color.red;
}
if (Input.GetMouseButtonDown (1))
{
gameObject.renderer.material.color = Color.green;
}
}
}
I would like to get this so it updates the block clicked instead of all of them at the same time. I searched the Q&A section here but could not find anything that would fix my issue. Thank you.
All you’re doing in your code is checking for mousebutton events. You need to tell the engine where the mouse cursor is, what object you’re clicking on. You also probably have this script attached to each cube, that’s why ALL of them are changing. Look into Raycast, and use ScreenPointToRay to define your Ray.
Here’s an example. Don’t forget to either rename the class in the script, or rename the script to match the class name. Attach THIS script to one object only, preferably the main camera.
using UnityEngine;
using System.Collections;
public class RaycastExample : MonoBehaviour
{
Ray ray;
RaycastHit hit;
void Update()
{
//Be sure to have a main camera that is tagged "MainCamera" for this example to work.
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
//Left Click, change to red.
if(Input.GetMouseButtonDown(0))
{
hit.collider.renderer.material.color = Color.red;
}
//Right Click, change to blue.
if(Input.GetMouseButtonDown(1))
{
hit.collider.renderer.material.color = Color.blue;
}
}
}
}
You can also use OnMouseOver function for this, which would be a simpler solution but require you to attach the script to every object you’ll need to click on. I’d tell you to use OnMouseDown, but OnMouseDown only detects left mouse button. Using OnMouseOver will allow you to detect that you’re hovering over the object, then use your Input instruction to determine the button pressed.
using UnityEngine;
using System.Collections;
public class OnMouseOverExample : MonoBehaviour
{
void OnMouseOver()
{
if(Input.GetMouseButtonDown(0))
renderer.material.color = Color.red;
if(Input.GetMouseButtonDown(1))
renderer.material.color = Color.blue;
}
}
Thank you very much for the help, both solutions worked perfectly. I did have the script attached to each cube. Now on to learn Raycast. Thanks again.
Thank you very much for the help, both solutions worked perfectly. I did have the script attached to each cube. Now on to learn Raycast. Thanks again.
– Domedi