- Home /
OnMouseDown on objects with tags
Hi all, I have here this script. using UnityEngine; using System.Collections;
public class CutTree : MonoBehaviour
{
public AudioClip treeChop;
public Transform player;
public float range;
//Below is doing stuff concerning what happens when clicked and if it is in range.
void OnMouseDown()
{
if(inRange())
{
audio.PlayOneShot(treeChop);
}
else
{
}
}
bool inRange()
{
if(Vector3.Distance(transform.position, player.position)<range)
{
return true;
}
else
{
return false;
}
}
I have assigned this to a tree in my game. If the player clicks on it, it plays a sound (but only if it is in range). It works fine. What I don't know how to do is assign this to the player, just for simplicity purposes and other things such as a woodCount or something. I was thinking of doing something with tags, such as
void OnMouseDown(gameObject.tag="tree")
{
}
Also, just on a sidenote, on the 'else' statement underneath the PlayOneShot, how can I make some gui text pop up saying "Not in range"? Preferably also with a tag, so I dont have to always add a text for every time something else is clicked.
Thanks a lot!
Answer by swifteria · Dec 25, 2014 at 08:56 AM
Thanks to everyone who replied. I simply have used raycasts and GameObject names and attached this to my player script. Everything works fine, thanks very much!
Answer by Divinyx · Dec 24, 2014 at 11:50 AM
Perhaps make the tree dependent on the player? like
Tree:
void OnMouseDown() {
player.Cut(gameObject)
}
Player
void Cut(GameObject tree){
if(inRange()) {
//play tree's cut audio
}
}
Answer by SkaredCreations · Dec 24, 2014 at 12:01 PM
OnMouseDown is called when the user clicks on the object where this method is attached, so you cannot move this in your player script because of course it would happen when the user clicks the player itself (if it has a collider). Instead I'd suggest to add a method in your player script and call SendMessage, for example:
Player script:
void DoStuff (GameObject go) {
// Do something, for example:
// if (go.CompareTag("myTag")) ...
}
Tree script:
void OnMouseDown()
{
if (inRange())
{
audio.PlayOneShot(treeChop);
player.SendMessage("DoStuff", gameObject);
}
}
Alternatively, if you want one only place to catch all the mouse clicks then you'll need to use Physics.Raycast with the ray from the main camera to Input.mousePosition inside Update of your player script.