簡體   English   中英

如何在Unity3D c#中聲明/使用getcomponent變量

[英]how to declare/use a getcomponent variable in Unity3D c#

我已經嘗試了許多小時,並且正在努力完成這項工作。

我需要從腳本中獲取一個變量並將其更改為+3

using UnityEngine;
using System.Collections;

    public class SwordKillScript : MonoBehaviour {

    public GameObject moneyAmount;
    private Component MoneyText;

    void Awake () { 
        moneyAmount = GameObject.FindGameObjectWithTag ("Money");
        MoneyText = moneyAmount.GetComponent<moneyText> ();
    }

    void OnCollisionEnter2D (Collision2D collisonInfo){
        Debug.Log ("Killed");
        if (collisonInfo.collider.tag != "Player") {
            MoneyText.money += 3;
            Destroy (collisonInfo.collider.gameObject);
        }
        transform.position = transform.position;
    }
}

那是一把劍的代碼,當它擊中一個物體時將其銷毀,然后應該在此腳本中添加+3:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class moneyText : MonoBehaviour {

    Text txt;
    public int money = 20;

    void Start () {
        txt = gameObject.GetComponent<Text>(); 
        txt.text= "$: " + money;
    }
}

任何幫助都很好,我希望這個問題易於閱讀和回答。

請盡可能簡單地回答,並說明原因,我最終將多次做這種事情,並且很想知道。

謝謝!

順便說一句:預計會出現錯誤,我需要知道我能做些什么來使這項工作-再次感謝。

編輯:這是我遇到更多麻煩的代碼,我在弄亂分配從字符串到getcomponent的所有東西,HALP!

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class MoneyText : MonoBehaviour {

    public GUIText txt;
    public int money = 20;

    public void ModifyMoney () {
        money += 3;
        txt.text = "$: " + money;
    } 
}

您的腳本沒有錯。 您將正確獲取組件,並正確增加值。 之所以可能看不到更新后的值,是因為您僅在Start()函數中設置了一次文本值。

txt.text= "$: " + money;

有很多更新文本的方法。 您可以執行以下任一操作

A)將moneyTexttxt變量公開。 然后在您的SwordKillScript ,可以添加以下行

MoneyText.money += 3; //You have this already moneyAmount.txt.text = "$: "+MoneyText.money; //Add this line


B)在moneyText類中編寫一個修改money值的方法。

public void ModifyMoney (int howMuch) {
    money += howMuch;
    txt.text = "$: "+money;
}

SwordKillScript調用此方法



C)你可以money的財產。

private int money = 20;
public int Money {
    get { return money; }
    set { 
        money = value;
        txt.text = "$ : "+money;
    }
}

然后,在SwordKillScript ,您只需要增加Money

PS您的命名約定有點差。 我可以建議您看看嗎? 例如,類名以大寫字母開頭(MoneyText代替moneyText)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM