- Home /
Trying to trigger multiple objects by holding down the mouse with OnMouseDown
Hey guys, need a little help with something. My scene consists of 4 spheres, and what I'm trying to achieve is when you click on one sphere, the colour of the sphere changes, and as you drag the mouse (while it's still held down) onto the other spheres, the other spheres change colour too. So far what I've managed to do is change the colour of the sphere when it's clicked, but I'm not able to change the colour of the other spheres when I drag the mouse onto them. I assume this is obviously because the code is only run when the mouse is first clicked. Is there a way to change this so a sphere changes colour when the mouse is clicked and dragged onto it? I've tried playing around with OnMouseDrag but with no success. Here's a link to a video of what I've got so far and what I'm trying to go for: https://youtu.be/KOBqnH0je6A
(All spheres have the same script attached) And here's my code:
public GameObject sphere;
public Material material;
void OnMouseDown()
{
sphere.GetComponent<MeshRenderer>().material = material;
}
Answer by yummy81 · Apr 21, 2020 at 05:14 PM
I wrote the script for you. Attach this script to each of your spheres. Then, in the inspector, drag and drop your desired material into "public Material material" variable. As you can see in the script, there is a bool called "pressed". Its aim is to keep track if the mouse button is pressed or not. The important thing is that this bool is "static". This guarantees that it is the same for all instances of your spheres. If the static modifier was absent, then there were as many bools "pressed" as is the number of spheres, and it wouldn't work as you expect. Try play with it. Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereScript : MonoBehaviour
{
public Material material;
MeshRenderer mr;
static bool pressed;
void Awake(){
mr = GetComponent<MeshRenderer>();
}
void OnMouseDown(){
mr.material = material;
pressed = true;
}
void OnMouseEnter(){
if (pressed){
mr.material = material;
}
}
void OnMouseUp(){
pressed = false;
}
}
Thank you so much! This is exactly what I needed. Stupid of me not to think of a static boolean facepalm
Thanks again!
Your answer
Follow this Question
Related Questions
C# Mouse Look (Input.GetAxis("MouseX&Y")) 0 Answers
Problem with dragging objects 1 Answer
Rotating object with a mouse movement 0 Answers
OnMouseDown is checked when build for Android 2 Answers
Get GameObject That Was Last Clicked? 2 Answers