c# - 如何从“B”预制对象访问“A”预制对象中的脚本?
问题描述
我正在尝试使用统一网络创建多人游戏。我创建了两个预制对象,一个是“玩家”预制对象,另一个是“子弹”预制对象。带有“播放器”预制件的健康脚本和带有“子弹”预制件的类似子弹脚本。但是当我尝试从'bullet' prefab 访问'player' prefab 中的公共方法时,我遇到了一个问题。
请帮助我如何解决它。
//::::::健康脚本:::::
using UnityEngine;
public class health : MonoBehaviour
{
public const int maxHealth = 100;
public int currentHealth = maxHealth;
public void takeDamage(int amount)
{
currentHealth -= amount;
if (currentHealth <= 0)
{
currentHealth = 0;
Debug.Log("player death");
}
}
}
//:::::子弹脚本:::::
using UnityEngine;
public class bullet : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
if(collision.collider.tag == "Player")
{
collision.gameObject.GetComponent<health>().takeDamage(10);
// OR
GameObject Em = collision.gameObject;
health healths = Em.GetComponent<health>();
if (healths != null)
{
healths.takeDamage(10);
}
// OR
GameObject clone = collision.collider.gameObject;
health myComponent = clone.GetComponent<health>();
myComponent.takeDamage(10);
}
Destroy(gameObject);
}
}
解决方案
推荐阅读
- javascript - 如何通过使用“Array(arrayLength)”初始化一个javascript数组来获取密钥?
- flutter - 如何在颤动中获取当前国家代码
- python - 按数组切片
- laravel - 使用 Gmail 发送电子邮件时 SSL 证书验证失败
- swift - 难以在 xcode 10 中向 imageview 添加约束。但无法将约束零添加到整个 imageView
- javascript - 跨多个页面持久化控制台命令
- python - 使用 subprocess 和 ffmpeg 从视频中提取声音
- r - R:将列表中的每个数据框与数据框中的不同列合并
- angular - IE SEC7111 HTTPS 安全性受到 http:// Angular 6 的威胁
- javascript - 按属性对对象中的列表进行分组