- Home /
How to access scripts in other game object with raycasts?
I'm trying to make a gun shoot and do damage to another object using raycast and the damage script is on the other object so i can remove health from that specific object, but I can't figure out how to access the script. This is what I have:
using UnityEngine;
public class Gun : MonoBehaviour {
public float damage = 10f;
public float range = 100f;
//The Script Variable
private MonoBehaviour enemyHealth = null;
public Camera cameraObject;
private void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
private void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(cameraObject.transform.position, cameraObject.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
//This is supposed to get the script from the object the Raycast hits
//The error is at the <EnemyHealth>
enemyHealth = hit.transform.GetComponent<EnemyHealth>();
if (enemyHealth != null)
{
//This is a public function from the other script
enemyHealth.Damage(damage);
}
}
}
}
Answer by Larry-Dietz · Dec 23, 2017 at 02:50 AM
Exactly what error are you getting? Is your Debug.Log statement showing the correct name for the object hit? Or are you just getting a null return value?
Just taking a quick look at your script, the first thing that stands out is your declaration of EnemyHealth.
Even if the return value was not null, I would expect an error when you tried to access Damage, as MonoBehavior doesn't have a method called Damage.
Just a shot in the dark, I am assume your script is called EnemyDamage, so I would try changing your declaration to Private EnemyHealth enemyHealth; and see if that changes anything.
If not, let us know exactly what error you are seeing.
Hope this helps, -Larry
The debug statement does show the correct name and the error is: namespace 'EnemyHealth' could not be found. I tried your suggestion but it gave me the same error
This is my other script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth : $$anonymous$$onoBehaviour {
public float health = 100;
public void Damage (float amount)
{
health -= amount;
if (health <= 0)
{
Die();
}
}
private void Die()
{
Destroy(gameObject);
}
}
This is the tutorial i'm using: https://www.youtube.com/watch?v=THnivyG0$$anonymous$$vo
but at the 7:30 mark where he does
Target target = hit.transform.GetComponent<Target>();
is where i got errors so i tried the monobehaviour thing
Answer by Matchewman023 · Dec 23, 2017 at 03:43 AM
I got it to work by taking the scripts out of my scripts folder and into the assets folder
That is odd. Your scripts folder is within your assets folder, is it not?