- Home /
Question by
arvidowic · Jul 21, 2020 at 02:14 PM ·
buttonbutton trigger events
How to add a button to that script? Or other solutions?
Hi everyone! I have a problem with my color changing script. The color of the object is not only changing when I tap on the object but also when I tap around the object. So what I need, is a limited area on the screen where I can tap on, to change the color (even if it is just a button on which I have to tap on (or if any of you may have an idea for that, a tap trigger set on the object)). If any of you could help me I´d be really thankful.
public class ColorChange : MonoBehaviour
{
public Color[] colors = new Color[] { Color.red, Color.blue, Color.green, Color.yellow };
public int currentColor, length;
private string CurrentColor;
private void Start()
{
currentColor = 0;
CurrentColor = string.Empty + currentColor;
length = colors.Length;
GetComponent<Renderer>().material.color = colors[currentColor];
}
private void Update()
{
if(MobileInput.Instance.Tap)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 5))
{
currentColor = (currentColor + 1) % length;
GetComponent<Renderer>().material.color = colors[currentColor];
}
}
}
}
Comment
Best Answer
Answer by Zoedingl · Jul 21, 2020 at 02:30 PM
Make a public function, which is changing the color. Then, add a button and add the function in the onClick field.