微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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++;

        }
    }

}

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

enter image description here

解决方法:

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

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

>您无法将场景中对象的引用分配给预制件.这根本不可能.预制件不应该知道现场.
>您可以将场景中的对象引用分配给同一场景中的另一个对象.
>您可以将预制件中(或在预制件内)的对象参考分配给任何对象(另一个预制件或相同的预制件或预制件内或场景中的对象)

换一种说法:

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

另类?

有许多.

为什么不尝试单身模式?它易于学习且易于使用.对于只有一个实例的对象来说无可挑剔.像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; }
}

在场景中有一个对象(最好是画布).将此脚本附加到它.在其中设置“我的文字”的参考.在你的碰撞脚本中只需调用GuiController.SetMyText(“得分:”得分)

编辑

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

每次具有此脚本的游戏对象被实例化时,Collisions中定义的字段分数将在新对象中重置为0.这是因为得分未被定义为碰撞的静态成员,并且任何新对象自然具有其自己的成员,即新得分.事实上,它不应该在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; } }
}

将脚本附加到游戏对象,而不是得分,你可以编写GameController.score;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐