首页 > 解决方案 > 如何从“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);
    }
}

在此处输入图像描述

在此处输入图像描述

标签: c#unity3d

解决方案


推荐阅读