我正在制作一款类似于太空射击游戏的游戏,我想知道如何防止玩家在弹药耗尽后射击弹丸。
以下两个脚本控制我的播放器的移动和动作,并在每次播放器击中空格键时减少当前的弹丸数量。
玩家脚本
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
//Movement speed of Player sprite
public float Speed = 20.5f;
//GameObject to store the projectile object
public GameObject Projectile;
// Update is called once per frame
void Update ()
{
//If left arrow key is pressed
if (Input.GetKey (KeyCode.LeftArrow))
//Move the player to the left
transform.Translate (new Vector2 (-Speed * Time.deltaTime, 0f));
//If right arrow key is pressed
if (Input.GetKey (KeyCode.RightArrow))
//Move the player to the right
transform.Translate (new Vector2 (Speed * Time.deltaTime, 0f));
//If the spacebar is pressed
if (Input.GetKeyDown (KeyCode.Space))
{
//Instatiate a new projectile prefab 2 units above the Player sprite
Instantiate (Projectile, transform.position + transform.up * 2, Quaternion.identity);
//Find the game object with the tag "Projectile" and call the DecreaseProjectileCount() function from the ProjectileTracker script
GameObject.FindGameObjectWithTag("Projectile").GetComponent<ProjectileTracker>().DecreaseProjectileCount();
}
}
}
ProjectileTracker脚本
using UnityEngine;
using System.Collections;
public class ProjectileTracker : MonoBehaviour {
//Variable to store the current projectile count
public GameObject ProjectileRef;
//Set the current projectile count to be 8
int CurrentProjectileCount = 8;
//Function to decrease the current projectile count
public void DecreaseProjectileCount()
{
//Decrease the current projectile count by 1
CurrentProjectileCount--;
//Print out the current projectile count
ProjectileRef.GetComponent<TextMesh> ().text = CurrentProjecileCount.ToString ();
}
}
感谢任何形式的帮助!
答案 0 :(得分:1)
我亲自这样做的方式:
ProjectileTracker tracker = GameObject.FindGameObjectWithTag("Projectile").GetComponent<ProjectileTracker>();
//If the spacebar is pressed
if (Input.GetKeyDown (KeyCode.Space) && tracker.ProjectileCount > 0)
{
//Instatiate a new projectile prefab 2 units above the Player sprite
Instantiate (Projectile, transform.position + transform.up * 2, Quaternion.identity);
//Find the game object with the tag "Projectile" and call the DecreaseProjectileCount() function from the ProjectileTracker script
tracker.ProjectileCount--;
}
...
using UnityEngine;
using System.Collections;
public class ProjectileTracker : MonoBehaviour {
//Variable to store the current projectile count
public GameObject ProjectileRef;
//Set the current projectile count to be 8
private int projectileCount = 8;
public int ProjectileCount
{
get { return projectileCount; }
set { SetProjectileCount(value); }
}
//Function to decrease the current projectile count
public void SetProjectileCount(int value)
{
projectileCount = value;
//Print out the current projectile count
ProjectileRef.GetComponent<TextMesh> ().text = value.ToString();
}
}