Hi,
I was looking for a way to use raycasts for my platformer player to shoot. I used the tutorial from Brackey’s
It’s the second half in case you’re unfamiliar ![]()
You can also download the project, which works totally fine as I can see, no errors etc.
https://github.com/Brackeys/2D-Shooting
However when I used the main script for shooting the raycast (RayCastWeapon.cs), I get an error.
Here’s the srcript:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayCastWeapon : MonoBehaviour {
public Transform firePoint;
public int damage = 40;
public GameObject impactEffect;
public LineRenderer lineRenderer;
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
StartCoroutine(Shoot());
}
}
IEnumerator Shoot ()
{
RaycastHit2D hitInfo = Physics2D.Raycast(firePoint.position, firePoint.right);
if (hitInfo)
{
Enemy enemy = hitInfo.transform.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
Instantiate(impactEffect, hitInfo.point, Quaternion.identity);
lineRenderer.SetPosition(0, firePoint.position);
lineRenderer.SetPosition(1, hitInfo.point);
} else
{
lineRenderer.SetPosition(0, firePoint.position);
lineRenderer.SetPosition(1, firePoint.position + firePoint.right * 100);
}
lineRenderer.enabled = true;
yield return 0;
lineRenderer.enabled = false;
}
}
The issue I seem to be having is with the line:
Enemy enemy = hitInfo.transform.GetComponent<Enemy>();
“Enemy” isn’t defined anywhere.
I’m using Unity 2020.3.9f1. I loaded the Brackey’s project into the same version which works.
What am I missing?
Jay.