(Unity)ビームソードの実装(Raycastの活用)

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BeamSword : MonoBehaviour
{
    public GameObject effectPrefab;
    public AudioClip sound;

    void Update()
    {
        RaycastHit hit;
        Ray ray = new Ray(transform.position, transform.forward);

        if(Physics.Raycast(ray, out hit, 100))
        {
            GameObject target = hit.collider.gameObject;

            if(target.CompareTag("Block"))
            {
                Destroy(target);
                GameObject effect = Instantiate(effectPrefab, target.transform.position, Quaternion.identity);
                Destroy(effect, 1.0f);
                AudioSource.PlayClipAtPoint(sound, transform.position);
            }
        }
    }
}

(実行結果)