- Home /
How to change sphere color when clicked?
I am trying to change the color of a sphere when I click on it. I am using this code
void OnMouseDown ()
{
rigidbody.useGravity = true;
renderer.material.color = Color.black;
}
}
This is in a script that I have given to my sphere. I am thinking my problem may be the sphere not knowing it has been clicked or something?
Answer by aldonaletto · Sep 08, 2013 at 06:41 PM
This should work - provided that the sphere has a collider, isn't hidden by another collider and isn't in the IgnoreRaycast layer. You should also make sure that the script is attached to the sphere (not to a child or parent), and that the shader doesn't ignore the material.color parameter. There's also an extra "}" in your code, but I suppose that it's a typo in the question. NOTE: OnMouseDown isn't emulated by touches - only a mouse or similar pointing device generates this event.
The sphere has a collider. I don't know anything about the IgnoreRaycast layer, and the shader is on diffuse. Still no luck making the color change though. Also that last "}" is a typo.
The diffuse shader is ok. I edited my answer and included other topics: is any collider hiding the sphere? (a transparent plane, for instance). Is this being tested in a touchscreen device? (On$$anonymous$$ouseDown don't work with touches). I tested your code and it worked fine with a Unity's sphere, as expected. Try to add a debug line:
void On$$anonymous$$ouseDown (){
print(name + " clicked");
rigidbody.useGravity = true;
renderer.material.color = Color.black;
}
I don't see any difference after adding the debug line. I see where it says IgnoreRaycast under layers and that is not checked.
Do you see something being written in the debug window when you click on the sphere? The debug window can be found in the Window -> Console menu.
It should say something like: "Sphere clicked". If it doesn't show, it means that the application is not able to detect the click itself, so the issue is not likely to reside in the code.
In the Edit -> Project Settings -> Physics menu, are all boxes selected? If not, try selecting all of them.
I'm not using a touchscreen device. Where are the results from the debug line supposed to print? I don't see anything different.
Answer by DDP · Sep 08, 2013 at 06:41 PM
You will want to add a SphereCollider component to your game object.