c# - 如何从 1 个脚本创建一个公共的“enemyDamage”整数,与另一个脚本通信?
问题描述
我是编码新手,不太确定如何将上下文从一个脚本添加到另一个脚本。到目前为止,对于我的游戏,我一直在使用来自多个来源的科学怪人代码,并且陷入了死胡同。我希望我的玩家受到与“敌人”脚本中enemyDamage 所述相同数量的伤害。我不太确定要给你什么其他背景,但如果你知道如何帮助我,那就太棒了!
敌人脚本
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public int health = 100;
public int enemyDamage = 10;
public GameObject deathEffect;
public void TakeDamage (int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
void Die ()
{
Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
PlayerHealth 脚本
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
public int maxHealth = 10;
public int currentHealth;
public int damage = 1;
public HealthBar healthBar;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
TakenDamage(1);
}
if (currentHealth <= 0)
{
PlayerDeath();
}
}
public void TakenDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
void PlayerDeath()
{
UnityEngine.Debug.Log("bean guy");
}
public void OnTriggerEnter2D(Collider2D hitInfo)
{
UnityEngine.Debug.Log("We did it boys");
PlayerHealth player = hitInfo.GetComponent<PlayerHealth>();
{
UnityEngine.Debug.Log("beans");
TakenDamage(enemyDamage); // I need this to update with enemyDamage 's value
}
}
}
解决方案
有多种方式:
使 EnemyDamage 成为静态变量
public static int enemyDamage = 10;
然后你可以在其他脚本中调用它Enemy.enemyDamage
请注意,您不能在 Inspector 中设置静态变量。
使用 GetComponent
Enemy enemy = gameObject.GetComponent(typeof(Enemy )) as Enemy;
enemy.enemyDamage
创建游戏管理器
游戏管理器.CS:
#region Singelton
public static GameManager instance;
void Awake()
{
if (instance != null)
{
Debug.LogWarning("More than one Instance of Inventory found");
return;
}
instance = this;
}
#endregion
public int enemyDamage = 10;
引用 GameManager 脚本:
GameManager gm;
void Start()
{
gm = GameManager.instance;
}
//Calling Function in GameManager
gm.EndGame();
// Getting Value from GameManager
gm.enemyDamage();
什么时候用什么?
- 如果您想要一个更短期的解决方案,我会使用静态变量,不建议使用多个敌人(不同的敌人伤害值现在是不可改变的)
- 如果您有更多变量甚至需要从多个脚本访问的函数,我建议您改用游戏管理器
- 您需要获取 Enemy 的引用才能使用 GetComponent,但可以添加多个不同的enemyDamage 值
推荐阅读
- javascript - React-native - SyntaxError: ..\src\screens\SignUp.js: Unexpected token, expected ";"
- python - Python SQL insert 语句只插入部分记录
- vb.net - 间隔时间VB.Net中的随机数
- node.js - (节点:9464)UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
- sql - 如何加入而不是工会
- regex - 如何定义正则表达式以从字符串中删除 [xx]xxxxx[arch] xxx?
- oracle - oracle如何调用触发函数
- python - 具有特定值的 Python 圆形数据框列(如果存在)
- javascript - 如何在单独的文件中隔离一些在反应组件中互连的功能
- vue.js - Vue动态组件覆盖