如何在unity3d中将硬币分数添加到当前分数

时间:2014-09-08 16:34:45

标签: unity3d

如何使用主分数添加硬币值?这意味着如果玩家收集硬币,他将获得与当前分数相关的每枚硬币25点。

using UnityEngine; 
using System.Collections;

public class PlayerScript : MonoBehaviour {

    public AudioSource audio1;
    public AudioSource audio2;
    public float offsetY = 40f;
    public float sizeX = 100;
    public float sizeY = 40;
    public Vector3 speed = new Vector3 (5f, 0f, 0f);
    public Vector3 jumpForce = new Vector3 (0f, 5f, 0f);
    private bool jump = true;
    private bool grounded = false;
    private bool doubleJump = false;

    void Start(){
        AudioSource[] audios = GetComponents<AudioSource>();
        audio1 = audios[0];
        audio2 = audios[1];
    }

    void FixedUpdate(){
        if (grounded)
            doubleJump = false;
    }

    void Update(){
        transform.Rotate (-5,15,10*Time.deltaTime); //rotates 50 degrees per second around z axis
        if ((grounded || !doubleJump) && jump) {
            rigidbody.AddForce (speed, ForceMode.Acceleration);

            // if(Input.GetMouseButtonDown(0))
            if (Input.GetButtonDown ("Jump"))
            {
                //Debug.Log("Hit da floor");
                rigidbody.AddForce (jumpForce, ForceMode.VelocityChange);

                if(!grounded)
                    doubleJump = true;
            }
        }
        //grounded = false;  
    }

    void OnCollisionEnter(Collision obj) {
        grounded = true;
        audio1.Play();
    }

    void OnCollisionExit(Collision obj) {
        grounded = false;
    }

    void OnTriggerEnter(Collider Coin){
        audio2.Play ();
        Destroy (Coin.gameObject);
    }

    void OnGUI() {
        GUI.color = Color.black;

        int currentScore = (int)transform.localPosition.x;
        int highScore = PlayerPrefs.GetInt ("highS", 0);

        if (currentScore > highScore) {
            PlayerPrefs.SetInt ("highS", currentScore);
        }
        GUI.Label (new Rect (Screen.width/4, offsetY, sizeX, sizeY ), "<color=red> Score: </color>" +"<color=white>" + currentScore + "</color>");
        GUI.Label (new Rect (Screen.width/21, offsetY, sizeX, sizeY ), "<color=red>Highscore:</color> " +"<color=white>" + highScore + "</color>");
        //GUI.Label (new Rect (Screen.width/11, offsetY, sizeX, sizeY ), "Coins: " + coins);
    }

1 个答案:

答案 0 :(得分:0)

假设您的评论,您希望每个硬币都有一个值:

为每枚硬币添加MonoBehaviour:

public class Coin:MonoBehaviour {
  public int coinVal=25; // default value, you can change it per each coin in the inspector
}

并更改OnTriggerEnter中的PlayerScript

void OnTriggerEnter(Collider c){ // some trigger was hit
  Coin coin=c.gameObject.GetComponent<Coin>();
  if(coin != null) { // a coin was hit
    score+=coin.coinVal;
    audio2.Play ();
    Destroy (coin.gameObject);
  }
}

在这里,我在您的课程中引入了score字段,因为OnGUI中的字段看起来像是临时修复。


您必须将硬币游戏对象设置为触发器,查看文档:{​​{3}}

另外,请注意,你不能在触发器上销毁它触及的所有东西,目前它已经。