【问题标题】:Unity Buttons Assignment [duplicate]Unity按钮分配[重复]
【发布时间】:2019-12-10 20:00:47
【问题描述】:

我对 C# 和 Unity 还很陌生,如果我的问题太简单了,很抱歉。 我正在尝试为每个统计数据创建一个由文本和按钮组成的简单升级系统。 我制作了文本脚本来显示我的“攻击伤害”统计数据,它有效。现在,我想创建一个脚本按钮,因此一旦单击它,我的统计信息将从(例如 10 到 11)或任何值。所以我的问题是:如何从另一个脚本访问变量,以便我可以通过单击按钮使用它们来递增? 我会附上两个脚本,请尽量简单地解释,以便新手能够理解。谢谢!

攻击伤害文本脚本(请记住,在 Player 类中 heroDamage 设置为 10f)

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

public class AttackDamage : MonoBehaviour
{
    public static float attackDamage = Player.heroDamage;

    public Text attackDamageText;

    // Start is called before the first frame update
    void Start()
    {
        attackDamageText.text = ADButton.attack.ToString(); //here it was attackDamage.ToString() at first but i wanted to see if it works like that.
    }

    // Update is called once per frame
    void Update()
    {

    }
}

攻击伤害按钮脚本:

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

public class ADButton : MonoBehaviour
{
    public Button attackDamageButton;

    public static float attack;

    // Start is called before the first frame update
    void Start()
    {
        attackDamageButton.onClick.AddListener(Update);
    }

    // Update is called once per frame
    void Update()
    {
        attack = AttackDamage.attackDamage;
        if (Input.GetMouseButtonDown(0))
            attack++;
    }
}

我猜我的第二个代码是错误的,但我不知道如何修改它。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    https://answers.unity.com/questions/1336162/how-to-reference-a-class-in-another-script-properl.html

    这显示了各种可能的方法。 但更简单的是对象引用。

    喜欢

    public class AttackDamage : MonoBehaviour 
    {
            // Start is called before the first frame update
            void Start()
            {
    
            }
    
    
            public void Method1()
            {
              // Do Something like Attack++;
            } 
    }
    
    public class ADButton : MonoBehaviour 
    {           
            public AttackDamage obj;
    
            // Start is called before the first frame update
            void Start()
            {
              obj.Method1();
            }
    
    
    }
    

    同样在这种情况下,您需要在具有 ADButton 脚本的 GameObject 的检查器中分配 AttackDamage 类。

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多