【问题标题】:pass int value from one script to another script in unity将 int 值从一个脚本统一传递到另一个脚本
【发布时间】:2023-06-30 19:08:02
【问题描述】:

我正在尝试将 public int score 值从一个脚本传递到另一个脚本,但它给了我错误 an object reference is required to access non-static member ,这就是我所做的

public class firearrow : MonoBehaviour {
    public GameObject Arrow;
    public GameObject apple;
    public int score = 0;


    // Use this for initialization
    void Start () {
        this.gameObject.GetComponent<Rigidbody2D> ().AddForce (transform.right*1500.0f);

    }


    // Update is called once per frame
    void Update () {
        Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        diff.Normalize();

        float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 0);

        if (Input.GetMouseButtonUp (0)) {


            GameObject bullet_new;

            bullet_new = Instantiate (Arrow,new Vector2 (-0.23f, -3.78f), Quaternion.identity) as GameObject;
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),Vector2.zero);
            if (hit.collider!= null ) {

                LeanTween.move(bullet_new,  hit.collider.transform.localPosition, 1);
                if(hit.collider.tag == "fruit")
                {           
                    score++;
                    Destroy(hit.collider.gameObject,1);
                    Destroy(bullet_new,1);
                }

            }


        }
    }




}

我要获取分数的班级

public class tick : MonoBehaviour {
    public Text wintext;
    // Use this for initialization
    void Start () {
        wintext.text = "";
    }

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

        if (Input.GetMouseButtonUp (0)) {

           if(firearrow.score == 3)
            {
                wintext.text="You Win";

            }


           }

    }
       }

有什么建议吗?

【问题讨论】:

  • 当变量未设置为静态时,您正尝试静态访问该变量。您需要在 tick 类中获取对“firearrow”脚本的引用。此外,您的命名约定非常糟糕。我建议您查看一些设计模式和基本教程,以便您了解事情的工作原理。

标签: unity3d unityscript


【解决方案1】:

换行

public int score = 0;

public static int score = 0;

请注意,您必须只有一个 firearrow 类实例,否则您可能会遇到并发问题。

【讨论】:

  • 非常感谢它的帮助!是的,我会记住这一点。
最近更新 更多