I need a command to select and change a single object

Hi there. I am working on a little game as a first time project and am having a bit of trouble doing what’s probably quite a simple thing to do. Basically i have a set of squares which i want to change colour on a click of the mouse. The script i created also checks to make sure that this can’t be done twice. It works fine with one square, but as soon as i have more than one square it selects them all simultaneously. Here is my script:

using UnityEngine;
using System.Collections;

public class A1 : MonoBehaviour {

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {
	if(gameObject.renderer.material.color!=Color.red && gameObject.renderer.material.color!=Color.blue)
	{
		ColourChanger();
	}
}

void ColourChanger()
{
			if (Input.GetMouseButtonDown (0)) {
				gameObject.renderer.material.color = Color.red;
			}
			if (Input.GetMouseButtonDown (1)) {
				gameObject.renderer.material.color = Color.blue;
			}
	}

}

What i want is for to be able to change only one of the squares. I think that it’s a prob with the ‘Input.GetMouseButtonDown (0)’ part as it’s too general and will effect everything no matter where i press the mouse button. Can anybody help me? Thanks

Use Physics.Raycast() to work out which square has been clicked on.

Thanks for the quick reply Graham

I did find a solution which also works… at the moment :slight_smile: ,
Here it is:

using UnityEngine;
using System.Collections;

public class A1 : MonoBehaviour {

void OnMouseOver() { //To ensure that only a specific square is targeted

 if (gameObject.renderer.material.color != Color.red && gameObject.renderer.material.color != Color.blue) { 
		ColourChanger();  //Calls my colour changer method
}
	}

void ColourChanger(){//My colour changer method
	if (Input.GetMouseButtonDown (0)) {
		gameObject.renderer.material.color = Color.red;
	}
	if (Input.GetMouseButtonDown (1)) {
		gameObject.renderer.material.color = Color.blue;
	}
}

}

With this you can change individual squares either red or blue permanently and also are unable to change the objects more than once… perfect, that is, probably until i write the main program to put it all together. I’ll keep the Physics.Raycast() solution in mind for when it does go wrong. And i’ll probably be back with more questions soon
Thanks again :slight_smile: