- Home /
Instantiate an object on mouse/cursor position.
I have 3 objects in scene. A cube, a sphere and a cone. I also have an array with the 3 objects i want to instantiate on each object on scene when the cursor is over them and destroyed when the mouse isn't over the object anymore.
The objects on the array are: bigger cube, bigger sphere and bigger cone. I know i could just edit the scale of the objects in scene if i want to make them bigger, but for this example i want to do it this way.
For example, bigger cube should only be instantiated if the cursor is over the cube object in scene and same thing with the sphere and cone and their bigger versions should be destroyed if the cursor isn't over the objects anymore.
How would a script to achieve this?
Answer by unity_ek98vnTRplGj8Q · Feb 16, 2021 at 06:07 PM
Use OnMouseEnter and OnMouseExit, and put this script on each small object
public GameObject bigObject;
private GameObject instBigObject;
void OnMouseEnter(){
instBigObject = Instantiate(bigObject, transform.position);
}
void OnMouseExit(){
Destroy(instBigObject);
}
You do need to make sure that the small objects each have colliders on them