Make object animate when mouse hovers over the top in 2D game

Im new to unity and wanted to find out if this effect was possible and how to do it.

Say you had an object on the ground in your 2D game. I want to make it so when you hover the mouse over the object it will animate (otherwise the object would be still). For example if you wanted to give it a glow, or make it vibrate or change colour or something like that.

Anyone know how to do this?

A little bit of googling can find a solution for almost everything:

Give the object a collider, and you can use OnMouseOver/OnMouseExit in a MonoBehaviour script attached to it.

 using UnityEngine;

public class Example : MonoBehaviour
{
    void OnMouseOver()
    {
        // do mouse hover stuff
    }

   void OnMouseExit()
   {
       // reset to normal
   }
}

From there you can do whatever you like, turn on another sprite, run an animation, change colors, etc.

3 Likes

Ah thanks so much. Im not at all familiar with code, but is there any where that can tell me what those different things mean and how to change them to what I need? Do you think that it is not really possible to use Unity without knowing code?

Thanks so much for your help.

Here’s a heavily commented version of that code:

using UnityEngine; // lets you access MonoBehaviour, GetComponent, and more

// This is a class named Example that inherits from MonoBehaviour, which gives it
// access to lots of events and useful functions, and means it is a Component, able to be
// attached to a GameObject in the Unity Editor

public class Example : MonoBehaviour
{
  // This is a MonoBehaviour-provided function that Unity will run one time
  // automatically when the cursor is over this GameObject
  // (GameObject needs a collider component)

  void OnMouseOver()
  {
      // in here you write code to respond to this event

      // Use GetComponent to find the SpriteRenderer component on this GameObject
      // then set its color to be green
      GetComponent<SpriteRenderer>().color = Color.green;
  }

  // This is a MonoBehaviour-provided function that Unity will run one time
  // automatically when the cursor is no longer over this GameObject
  // (GameObject needs a collider component)

   void OnMouseExit()
   {
      // in here you write code to respond to this event

      // Use GetComponent to find the SpriteRenderer component on this GameObject
      // reset it to normal color
      GetComponent<SpriteRenderer>().color = Color.white;
   }
}

I don’t think that it’s impossible to use Unity without coding, but you’ll be very limited to what you can create.

You might be interested in checking out Unity’s 2D Game Kit, which has a lot more components and tools to create actual gameplay with.