How do I get points when clicking an object?
Hi.
I'm new to Unity scripting. I've made two scripts. One that adds 1 point to my score when I click on the object with the script and one that manages it and displays it on my HUD. It kinda works, but I can do it from all lengths. I want to be in reach of the object before I get points. How can I do that?
public class Counter : MonoBehaviour {
private float pettingFinished = 0;
public void OnMouseUp()
{
Debug.Log("I've been clicked"); //For debugging purpose
if (Time.time > pettingFinished)
{
ScoreCounter.score += 1; //Adds 1 point to the score
pettingFinished = Time.time + 1;
}
}
}
the other script:
public class ScoreCounter : MonoBehaviour {
static public int score = 0; //player score
Text uiText;
void Awake()
{
uiText = GetComponent<Text>(); //Set up the reference.
score = 0; //Reset the score.
}
void Update ()
{
uiText.text = "Score: " + score; // Set the displayed text to be the word "Score: " followed by the score value.
}
}
Thanks in advance
Answer by Jessespike · Jan 27, 2016 at 08:38 PM
Have you tried Vector3.Distance? You'll need to provide positions for the distance calculation.
float distance = Vector3.Distance( playerTransform.position, pointTransform.position);
if (Time.time > pettingFinished && distance < 3f)
{
ScoreCounter.score += 1; //Adds 1 point to the score
I haven't tried that. Sadly, I do not understand how it works.
I know that Vector3 is something to do with the position (x,y,z), but I don't know much more than that.
Can you elaborate?
Not sure if I can explain clearly. Here goes:
Vector3 is a struct that contains 3 floats (x,y,z)
Every GameObject has a Transform component, The Transform component stores the GameObject's position, rotation and scale.
So in a script you can get an object's position from it's transform.
public Transform myPlayerTransform;
void Start() {
Debug.Log("myPlayerTransform's position is " + myPlayerTransform.position);
}
$$anonymous$$aybe Unity can explain it better:
http://docs.unity3d.com/$$anonymous$$anual/class-Transform.html
Your answer
Follow this Question
Related Questions
How to add a score in unity? 0 Answers
Anyway To Set A Specific Part Of Code To A Scene? 2 Answers
Scoring different amount of points 0 Answers
Highscore and PlayerPrefs unity C# 1 Answer
Highscore system unity C# 0 Answers