【问题标题】:Can't figure out how to access an int from another script无法弄清楚如何从另一个脚本访问 int
【发布时间】:2019-03-20 20:22:45
【问题描述】:

我知道之前有人问过这个问题,herehere
但我仍然无法从另一个脚本中获取变量。我不知道我做错了什么。
*(总的来说,我对编程很陌生,所以我可能错过了一些明显的东西)

我不断收到错误:The name 'points' does not exist in the current context

slimespawner 脚本在画布上。

对不起,如果问题太简单了。

这是我要访问的脚本:

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

public class slimespawner : MonoBehaviour
{
    public int points;
    public Text score;
    public float xx;
    public float yy;

    void Start()
    {
        points = 0;
        xx = Random.Range(-32f, 32f);
        yy = Random.Range(-18.5f, 18.5f);
    }

    void Update()
    {
        score.text = "Score: " + points.ToString();
    }
}

这是尝试使用 points 变量的脚本。

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

public class slimecontroller : MonoBehaviour
{
    private float movespeed = 0.1f;
    public slimespawner slisp;

    void Start()
    {
        slisp = GameObject.Find("Canvas").GetComponent<slimespawner>();
    }
    void Update()
    {
        points += 1;
    }
}

【问题讨论】:

  • 你试过base.points吗??
  • 他的意思是slisp.points。请注意,如果您在 Inspector 中正确引用它,则不需要整个 GameObject.Find("Canvas").GetComponent&lt;slimespawner&gt;();

标签: c# unity3d


【解决方案1】:

您的代码应如下所示:

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

public class slimecontroller : MonoBehaviour
{
    private float movespeed = 0.1f;
    public slimespawner slisp;

    void Start()
    {
        slisp = GameObject.Find("Canvas").GetComponent<slimespawner>();
    }
    void Update()
    {
        slisp.points += 1;
    }
}

【讨论】:

  • 请注意,如果您在 Inspector 中正确引用此内容(因为它是公开的),您不需要整个 GameObject.Find("Canvas").GetComponent&lt;slimespawner&gt;();
【解决方案2】:

使用slisp.points += 1;访问该属性

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2018-08-15
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多