繁体   English   中英

如何使用c#从代码中分配gameObject

[英]how can assign a gameObject from code using c#

我正在研究随机硬币发生器。 我已经包含以下代码:

timer -= Time.deltaTime;

if (timer <= 0)
{

    Vector3 position = new Vector3(Random.Range(11f, 14f), Random.Range(-0.7f, 4.5f), 0);
    Instantiate(coins, position, transform.rotation);
    timer = delayTimer;
}

然后我添加一个碰撞来挑选硬币并制作一个得分文本:

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

public class Collisions : MonoBehaviour {
    public  Text scoreText;
    private float score;
    // Use this for initialization
    void Start () {
    }

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

        scoreText.text = "Score : " + score;



    }

    private void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            Destroy(gameObject);
            scoreText.text = "Score : " + score;
            score++;

        }
    }

}

所以现在当我需要将文本添加到预制件时我不能,如果我以某种方式将文本分配给预制件,则不计算任何分数

在此输入图像描述

您需要一个脚本或预制件来了解场景中的某个对象。 对?

每当你发现自己处于这种情况时,你必须修改你的方法。 记住:

  • 您无法将场景中对象的引用分配给预制件。 这根本不可能。 预制件不应该知道现场。

  • 可以将对象的引用从场景分配给同一场景中的另一个对象。

  • 可以将预制件中(或在预制件内)的对象参考分配给任何对象(另一个预制件或相同的预制件或预制件内或场景中的对象)

换一种说法:

除了从场景到预制,你可以拖放任何地方

另类?

有许多。

为什么不尝试单身模式? 它易于学习且易于使用。 对于只有一个实例的对象来说无可挑剔。 像GameController或GuiController或UserProfileController等。

有单身GuiController:

public class GuiController : MonoBehaviour
{
    //singleton setup
    static GuiController instance;
    void Awake() { instance = this; }

    //now it's ready for static calls

    public UnityEngine.UI.Text MyText;

    //static method which you can call from anywhere
    public static void SetMyText(string txt) { instance.MyText.text = txt; }
}

在场景中有一个对象(最好是画布)。 将此脚本附加到它。 在其中设置“ My Text的参考。 在你的碰撞脚本中只需调用GuiController.SetMyText("Score : " + score)

编辑

碰撞脚本实际上有一点错误。

每次具有此脚本的游戏对象被实例化时, Collisions定义的字段score将在新对象中重置为0。 这是因为score未定义为Collisions的静态成员,任何新对象自然都有自己的成员即新得分。 事实上,它不应该在Collisions ,最好让GameController脚本处理这些类型的数据。

再次使用单例模式:

public class GameController : MonoBehaviour
{
    static GameController instance;
    void Awake() { instance = this; }

    float score;
    public static float Score { get { return instance.score; } set { instance.score = value; } }
}

将脚本附加到游戏对象而不是score++您可以编写GameController.Score++ ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM