I am working on a small prototype for a project, this is my first experience with Unity or C#. I have put together what I have so far by reading documentation, following tutorials, and trial and error.
To try and help explain my problem, I have uploaded a web player of it so far, including underneath all my code, and screenshots of the inspector panels. You can also download a zip of the project if that isn’t enough (let me know if this doesn’t work or I didn’t pack it correctly). I apologise if any of my files or code are messy, I’ve tried to keep them neat enough. All of this can be found here:
http://aiden.lesanto.com/Build1_2/Build1_2.html
Basically, I am trying to make the Player collect the pink objects (eggs) and then have a counter (top left) keep track of how many he has collected so far. The objects ‘magnetise’ towards him when he gets near, using a separate Gameobject with a collision area that is a trigger. When the player is in the trigger the item moves towards him and the object is then destroyed so it looks like he has collected it.
It is the counter that is my problem. If the player moves within the trigger boundary, and stays still until the object moves towards the player, he collects it but it does not add to the value ‘Score’. However, if the player moves quickly over where the object is before allowing it to move towards him, it sometimes does add to the Score. It doesn’t really add correctly, sometimes it multiplies too many times.
Could anybody take a look at this and help me figure out how to make it behave correctly? I’ve been stuck for days, but I feel that it might be obvious to someone more experienced. Any advice is appreciated.
Here is some of the code:
coinCollect.cs
public class coinCollect : MonoBehaviour {
// Script Reference
public timerText timerText;
//
public int value;
void OnTriggerEnter2D(Collider2D collidedObject)
{
if (collidedObject.tag == "Player")
{
collidedObject.GetComponent<CoinCounter>().score += value;
timerText.timer += 1;
}
}
}
CoinCounter.cs
public class CoinCounter : MonoBehaviour {
public int score;
public GUIText EggCount;
public int maxEggs = 250;
void Update (){
EggCount.text = "Eggs " + score + " / " + maxEggs;
}
}
MagnetMove.cs
public class MagnetMove : MonoBehaviour {
public Transform target;
public float speed;
void OnTriggerStay2D(Collider2D collidedObject)
{
if (collidedObject.tag == "Player")
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
Destroy(gameObject,0.25f);
}
}
}
timertext.cs
using UnityEngine;
using System.Collections;
public class timerText : MonoBehaviour {
public GUIText timeText;
// The countdown timer
public float timer;
// Update is called once per frame
void Update () {
timer -= Time.deltaTime;
timeText.text = "Time " + timer.ToString ("0");
if (timer <= 0){
timeText.text = "";
Time.timeScale = 0;
}
}
}
There is more detail in the link above if this is not enough