Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Game Development

Rory Letteney
Rory Letteney
1,342 Points

OnMouseOver() and OnMouseExit() - C#

Hello! I am trying to instantiate a number of planes to use as my terrain and give them OnMouseOver() to change them to some color and OnMouseExit() to change them back to the original color. I attached a plane instantiation script to the main camera to generate the plane prefab and a mouse event script to the plane prefab. I get them all instantiated and the events pass to them, but in-game the mouse events are being applied to either long strips of planes, an entire quadrant, or a random single plane not at the location of the mouse cursor. I am not sure what to do.

public class TerrainGeneration : MonoBehaviour {

[SerializeField]
private Transform groundTile;
private Vector3 row;

// Use this for initialization
void Start () {

    for ( int i = 0; i <= 10; i++)
    {
        for (int x = 0; x <= 10; x++) {

            row = new Vector3(i, 0, x);
            Instantiate(groundTile, row, Quaternion.identity);

        }    
    }
}

}

public class MouseEvents : MonoBehaviour {

private Color isTargeted;
private Color notTargeted;
private MeshRenderer groundTileMeshRenderer;

void Start () {

    groundTileMeshRenderer = gameObject.GetComponent<MeshRenderer>();
    isTargeted = Color.cyan;
    notTargeted = groundTileMeshRenderer.material.color;

}

void OnMouseOver()
{
    groundTileMeshRenderer.material.color = isTargeted;
}

void OnMouseExit()
{
    groundTileMeshRenderer.material.color = notTargeted;
}

}

1 Answer

Rory Letteney
Rory Letteney
1,342 Points

I found the answer. I was not accounting for the size of the plane when instantiating and setting the transform. I was instantiating at Vectors increasing such as (0,0,0), (0,0,1), (0,0,2) when the plane primitive 3d object is 10x10 units in size. The fix was as simple as the following:

row = new Vector3(i * 10, 0, x * 10);
Instantiate(groundTile, row, Quaternion.identity);