如何从我的 Raycast 命中的游戏对象引用脚本?

问题描述 投票:0回答:1

我一直在尝试从我的光线投射命中的游戏对象引用脚本,但我无法让它工作,应该发生的是当光线投射命中游戏对象时,它会检查其标签是否为“僵尸”并且如果是,那么它将访问该对象的 ZombieHealth 脚本,然后 Dead 应该 = true

这是拍摄光线投射的 Gun 脚本

using UnityEngine;

public class Gun : MonoBehaviour
{
    public GameObject cannonBall;
    public Transform spawnPoint;
    public AudioSource audioSource;
    public AudioClip fireSound;
    Ray ray;





    private void Update()
    {

        if (Input.GetButtonDown("Fire1"))
        {
            RaycastHit hit;
            audioSource.PlayOneShot(fireSound);
            ParticleSystem ps = GameObject.Find("SmokeEffect").GetComponent<ParticleSystem>();
            ps.Play();

            if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit))
            {
                if (hit.collider.gameObject.CompareTag("Zombie"))
                {
                    Debug.Log("ZOMBIE HIT KO KO KO KO KO KO");

                    hit.collider.gameObject.GetComponent<ZombieHealth>();
                }
            }
        }
}   }

这是僵尸的脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.ProBuilder;

public class ZombieHealth : MonoBehaviour
{
    public GameObject DeadZombie;
    public bool Dead;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

        
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (Dead == true)
        {
            Destroy(gameObject);
            GameObject clone;
            clone = Instantiate(DeadZombie, transform.position, transform.rotation);

        }
    }
}

我尝试了无数的网站试图找出我做错了什么,但我无法弄清楚

c# unity-game-engine raycasting
1个回答
0
投票

向您的僵尸游戏对象添加一个脚本,以便每个僵尸上都会有相同的脚本。在该脚本中创建一个函数,在调用脚本时销毁僵尸(在本例中为父游戏对象僵尸)。

然后在 if (hit.collider.gameObject.CompareTag("Zombie")) 代码中添加一些将访问该脚本并调用 destroy 函数的代码。它看起来像这样:

if (hit.collider.gameObject.CompareTag("Zombie")){
    GameObject zombieToDestroy = hit.collider.gameObject; //create a gameobject that you can reference from that hit by the raycast.
    destoryScript desScript = zombieToDestroy.GetComponent<destoryScript>(); //create a reference to the destory script.
    desScript.destroyZombie(); //destroy the Zombie.

}

还有其他更简洁的方法可以做到这一点,所以可以尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.