gpt4 book ai didi

javascript - Unity脚本全局变量

转载 作者:行者123 更新时间:2023-12-03 06:52:06 31 4
gpt4 key购买 nike

我有一个名为“死亡”的脚本,当碰撞成立时,它会在起始位置重新生成玩家。我试图计算分数,当这次碰撞为真时,它将减去 100 分,但没有成功。以下脚本来自得分和死亡脚本。任何帮助将不胜感激。

评分脚本:

    var gui : GameObject;
static var score : int;
Death.death = false;

function Start ()
{
gui.GetComponent ("GUIText").text = "Score: 0";
}


function Update ()
{
gui.GetComponent ("GUIText").text = "Score: " + score;
if (death)
{
score = score - 100;
}
}

死亡脚本:

#pragma strict 
var Ball : Transform;
public var death : boolean = false;

function OnCollisionEnter (b : Collision)
{
if (b.gameObject.tag == "Ball")
{
death = true;
Ball.transform.position.x = 1.6;
Ball.transform.position.y = 1.5;
Ball.transform.position.z = 1.1;
Ball.GetComponent.<Rigidbody>().velocity.y = 0;
Ball.GetComponent.<Rigidbody>().velocity.x = 0;
Ball.GetComponent.<Rigidbody>().velocity.z = 0;
}
}

最佳答案

尽管我使用的是 C#,但我希望能够帮助您。将其转换为 UnityScript 应该很容易。

using UnityEngine;

public class Score : MonoBehaviour
{
public GUIText guiText;
int score;

void Update()
{
if(DeathTrigger.wasTriggered)
{
DeathTrigger.wasTriggered = false;
score -= 100;
}
guiText.text = string.Format("Score: {0}", score);
}
}

public class DeathTrigger : MonoBehaviour
{
public static bool wasTriggered;

void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Ball"))
{
wasTriggered = true;
// ...
}
}
}

我认为这是一个初学者的问题,所以我不会说任何关于静态变量如何邪恶之类的事情,但我仍然想发布一个示例,说明下一步该去哪里寻找更好的方法:

using System;
using UnityEngine;
using UnityEngine.UI;

public class BetterDeathTrigger : MonoBehaviour
{
// This event will be called when death is triggered.
public static event Action wasTriggered;

void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Ball"))
{
// Call the event.
if (wasTriggered != null)
wasTriggered();
// ...
}
}
}

public class BetterScore : MonoBehaviour
{
public Text uiText; // Unity 4.6 UI system
int score;

void Start()
{
// Subscribe to the event.
BetterDeathTrigger.wasTriggered += WasTriggered_Handler;
}

// This method will now be called everytime the event is called from the DeathTrigger.
private void WasTriggered_Handler()
{
score -= 100;
uiText.text = string.Format("Score: {0}", score);
}
}

有几件事:

  • GUIText 相当旧,自 Unity 4.6 版本以来已被新的 UI 系统取代
  • 从长远来看,静态变量并不智能,更喜欢对象实例,除非您非常确定静态变量是如何工作的
  • 这是在何处使用事件的一个很好的示例。同样,它是静态的可能会导致问题,但对于第一个示例来说,这是最简单的。
  • Unity Learn 网站提供了大量有关编程概念的教程,例如“脚本之间的通信”,它们还提供了基本的游戏示例,您可以在其中完成一个完整的项目。

关于javascript - Unity脚本全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37449568/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com