如何使用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++;
}
}
}
所以现在当我需要将文本添加到预制件时我不能
如果我以某种方式将文本分配给预制件,则不计算任何分数
解决方法:
您需要一个脚本或预制件来了解场景中的某个对象.对?
每当你发现自己处于这种情况时,你必须修改你的方法.记住:
>您无法将场景中对象的引用分配给预制件.这根本不可能.预制件不应该知道现场.
>您可以将场景中的对象引用分配给同一场景中的另一个对象.
>您可以将预制件中(或在预制件内)的对象参考分配给任何对象(另一个预制件或相同的预制件或预制件内或场景中的对象)
换一种说法:
除了从场景到预制,你可以拖放任何地方
另类?
有许多.
为什么不尝试单身模式?它易于学习且易于使用.对于只有一个实例的对象来说无可挑剔.像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;
标签:c,unity3d,unity5 来源: https://codeday.me/bug/20190623/1266700.html