提问人:GreekRussian 提问时间:11/1/2023 更新时间:11/1/2023 访问量:28
如何从光线投射命中的游戏对象中引用脚本?
How do I reference a script from the Gameobject my Raycast has hit?
问:
我一直在尝试从我的光线投射命中的游戏对象中引用脚本,但我无法让它工作,应该发生的事情是,当光线投射击中游戏对象时,它会检查其标签是否为“Zombie”,如果是,那么它将访问该对象的 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);
}
}
}
我尝试了无数的网站,试图弄清楚我做错了什么,但我无法弄清楚是否
答:
0赞
Overture
11/1/2023
#1
将脚本添加到僵尸游戏对象中,以便每个僵尸上都有相同的脚本。在该脚本中创建一个函数,该函数在调用脚本时销毁僵尸(在本例中为父游戏对象 Zombie)。
然后在 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.
}
还有其他更干净的方法可以做到这一点,所以可以玩一下。
评论