Reputation: 1
I have been trying to reference the script from the gameobject my raycast hits, and I am having trouble getting it to work, what is supposed to happen is when the Raycast hits a gameobject, it will check if its tag is "Zombie" and if it is then it will access the ZombieHealth script of that object and then Dead is supposed to = true
here is the Gun script that shoots the raycast
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>();
}
}
}
} }
and this is the script for the zombie
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);
}
}
}
I have tried countless websites trying to figure out what I am doing wrong but I cant figure if out
Upvotes: 0
Views: 124
Reputation: 101
Add a script to your Zombie gameobject so that every zombie will have this same script on it. Create a function in that script that destroys the zombie when the script is called (in this case the parent game object the Zombie).
Then in your if (hit.collider.gameObject.CompareTag("Zombie")) code add some code that will access that script and call the destroy function. It will look something like this:
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.
}
There are other and cleaner ways to do this so play around with it.
Upvotes: 0