我正在制作一个突破性的游戏,我想添加一个健康条,当球接触到带有“危险”标签的特定对象时,它会减少。我有一个游戏管理器脚本和一个拾取交互脚本,但就我设置它的方式而言,我有点困惑于如何从我的GM脚本到我的拾取脚本触发takedamage,考虑到我把playerhealth元素放到了GM脚本中,所以我可以将它附加到调用Game Manager的空游戏对象中,因为实际的玩家不在层次结构中,而是在运行时实例化的。我希望我不需要为了这个目的而重做整个事情。如果有人能帮我解决这个问题,我将不胜感激。
下面是我的GM脚本:
public class GM : MonoBehaviour
{
public int lives = 3;
public int bricks = 20;
public float resetDelay = 1f;
public Text livesText;
public GameObject gameOver;
private GameObject clonePaddle;
public GameObject youWon;
public GameObject bricksPrefab;
public GameObject paddle;
public GameObject deathParticles;
public static GM instance = null;
public int startingHealth = 100;
public int currentHealth;
public Slider healthSlider;
bool isDead;
bool damaged;
void Awake()
{
currentHealth = startingHealth;
TakeDamage(10);
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
Setup();
}
public void TakeDamage(int amount)
{
damaged = true;
currentHealth -= amount;
healthSlider.value = currentHealth;
if (currentHealth <= 0)
{
LoseLife();
}
}
public void Setup()
{
clonePaddle = Instantiate(paddle, transform.position, Quaternion.identity) as GameObject;
Instantiate(bricksPrefab, transform.position, Quaternion.identity);
}
void CheckGameOver()
{
if (bricks < 1)
{
youWon.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
if (lives < 1)
{
gameOver.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
}
void Reset()
{
Time.timeScale = 1f;
Application.LoadLevel(Application.loadedLevel);
}
public void LoseLife()
{
lives--;
livesText.text = "Lives: " + lives;
Instantiate(deathParticles, clonePaddle.transform.position, Quaternion.identity);
Destroy(clonePaddle);
Invoke("SetupPaddle", resetDelay);
CheckGameOver();
}
void SetupPaddle()
{
clonePaddle = Instantiate(paddle, transform.position, Quaternion.identity) as GameObject;
}
public void DestroyBrick()
{
bricks--;
CheckGameOver();
}
}下面是我的接机脚本:
public class Pickups : MonoBehaviour {
public float PaddleSpeedValue = 0.5f;
private bool isActive = false;
public float thrust=20f;
public Rigidbody rb;
GameObject player;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Hazard")
{
isActive = true;
Destroy(other.gameObject);
}
}
}发布于 2017-10-21 03:29:15
Pickups类根本不应该有或存储对播放器的引用(尽管您的问题不清楚这是一个附加到播放器上的脚本还是附加到其他东西上的脚本)。你的游戏管理器类应该。毕竟,负责管理包括玩家在内的游戏的是类。在那里,您可以使用GetComponent<?>()访问附加到播放器GameObject的任何脚本。
然后,因为GM包含对自身的公共静态引用,所以任何其他类都可以通过根据需要执行GM.instance.player来获得对播放器的引用,即使播放器被创建和销毁了几次(因为GM应该总是有对当前播放器的引用!)
假设clonePaddle字段就是播放器(的GameObject),您所要做的就是将其公开。
https://stackoverflow.com/questions/46855541
复制相似问题