Hi there I had this almost properly, but when I pressed the input to lower health, it would work only on all the enemies, not just the one that was being interacted with. So I determined that my raycast is working up to a point, just something in the syntax of actually applying the RaycastHit variable of whatIHit to the specific enemy it is hitting while also allowing the damageEnemy function to work. I’m making it sound more complicated then it is, here is the player script:
Using System.Collections;
public class Player : MonoBehaviour {
public int PHealth = 10;
public EnemyHealth enemyScript;
public bool damageE1 = false;
public float moveSpeed;
public GameObject Target;
public Material TargetMaterial;
public bool interact = false;
public Transform lineStart, lineEnd;
RaycastHit2D whatIHit;
void Update ()
{
Raycasting ();
float h = Input.GetAxis ("Horizontal") * moveSpeed;
transform.Translate (new Vector3 (h, 0));
float j = Input.GetAxis ("Vertical") * moveSpeed;
transform.Translate (new Vector2 (0, j));
}
void Raycasting()
{
Debug.DrawLine (lineStart.position, lineEnd.position, Color.green);
if (Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Guard"))) {
whatIHit = Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer ("Guard"));
interact = true;
} else {
interact = false;
}
if (Input.GetKeyDown (KeyCode.E) && interact == true) {
whatIHit.collider.gameObject.GetComponent<EnemyHealth>().DamageE1();
// DamageE1();
}
}
//
void OnCollisionEnter2D (Collision2D col)
{
if (col.gameObject.tag == "Enemy" || col.gameObject.tag == "Guard") {
Debug.Log ("player has collided with tagged enemy");
rigidbody2D.AddForce (new Vector2 (-200f, 100f));
PHealth -= 1;
}
}
void OnTriggerEnter2D (Collider2D col)
{
if(col.gameObject.tag == "Trig01" && Target != null)
{
Target.rigidbody2D.AddForce (new Vector2(-200f, 200f));
}
if (col.gameObject.tag == "Trig02" && Target != null)
{
Target.rigidbody2D.AddForce (new Vector2(200f, 200f));
}
}
}
And the much simpler enemy script:
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
public Player playerScript;
public int EHealth = 100;
void DamageE1()
{
Debug.Log ("Got to minus 1 EHealth in DamageE1 function");
EHealth -= 1;
}
void DestroyE1(){
if (EHealth <= 0) {
Destroy (gameObject);
}
I know that the problem is isolated in the
if (Input.GetKeyDown (KeyCode.E) && interact == true) {
whatIHit.collider.gameObject.GetComponent<EnemyHealth>().DamageE1();
}
Part of the player script, and the only error I am geting anymore is this weird:
Assets/Player.cs(37,106): error CS0122: `EnemyHealth.DamageE1()' is inaccessible due to its protection level
Any help would be greatly appreciated, and I will be sure to pay the help back soon, as I’m actually getting quite a bit better at this stuff slowly despite the few remaining hang-ups of things like this. Cheers!