How dose getcomponent work
So I have ray shoting out but script is not working .
using UnityEngine; using System.Collections;
public class RAY : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0)) {
RayClick ();
}
}
void RayClick()
{
RaycastHit hit = new RaycastHit ();
if (Physics.Raycast (transform.position, transform.forward, out hit)) {
actorenemymanager rc = hit.transform.GetComponent<actorenemymanager>();
if (rc != null)
rc.damage (50);
}
}
}
Is on player thats shoting and using UnityEngine; using System.Collections;
public class actorenemymanager : MonoBehaviour { public float health = 150; void Start () {
}
// Update is called once per frame
void Update () {
}
public void damage(float damagerecived){
health -= damagerecived;
if (health < 0) {
Destroy (gameObject);
}
}
}
is on the enemy , in console it detects that its hiting enemy but no health arent reduced .
Answer by milleniu · Jan 11, 2017 at 01:51 PM
Those script are working fine in my test environment :
Script on player :
using UnityEngine;
public class Ray : MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown (0)) {
RayClick ();
}
}
void RayClick() {
RaycastHit hit = new RaycastHit ();
if (Physics.Raycast (transform.position, transform.forward, out hit)) {
Debug.Log("Hit " + hit.transform.name);
ActorEnemyManager actorEnemyManager = hit.transform.GetComponent<ActorEnemyManager>();
if (actorEnemyManager != null) {
Debug.Log("Found");
actorEnemyManager.Damage(10);
}
}
}
}
Script on enemy :
using UnityEngine;
public class ActorEnemyManager : MonoBehaviour {
[SerializeField] float life = 150.0f;
public void Damage (float _damage) {
life -= _damage;
if (life <= 0) {
Destroy(gameObject);
}
}
}
If that doesn't work out for you, could you post screenshots of you did your setup for your scene and scripts ?
From what I see on those two screens, there is no reason it shouldn't be working. One possible error could be having multiple enemyactormanager script with different uppercase and you're calling the wrong one from your ray script. Also I noticed those two screens were taken without the above solution, I'm not saying your code shouldn't work, but at least I'm 100% sure the above two did the job in their test environment. $$anonymous$$aybe if you don't $$anonymous$$d posting a zip with your assets (unless you want to keep some things private) I could give a quick look a check if I find something.
Your answer
![](https://koobas.hobune.stream/wayback/20220612104606im_/https://answers.unity.com/themes/thub/images/avi.jpg)