LoginSignup
5
4

More than 3 years have passed since last update.

【Unity】マウスがオブジェクトに重なったらアウトラインを出す(自分用)

Last updated at Posted at 2020-11-09

ezgif.com-gif-maker (1).gif

アセットストアで「Quick Outline」というアセットをダウンロード。
“shot” 2020-11-09 23.56.55.png

適当にキューブとからのゲームオブジェクトを作成。

ダウンロードしたアセットの中に「Outline」というスクリプトがあるのでそれをアウトラインをつけたいオブジェクトにつける。
(今回はキューブ)
インスペクタービューでアウトラインの色や太さを変えれるのでお好みで変更する。

「cube」というタグを作り今作ったキューブのタグを「cube」にする。

↓のスクリプトをからのオブジェクトにつける

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

public class raymanejer : MonoBehaviour
{

    void Start()
    {

    }

    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit = new RaycastHit();

        if (Physics.Raycast(ray,out hit))
        {
            //レイが当たったタグがcubeならアウトラインスクリプトをON
            if (hit.collider.tag == "cube")
            {
                hit.collider.GetComponent<Outline>().enabled = true;
            }
            ///レイが当たったオブジェクトのタグがcubeではなかったらcubeタグを持つオブジェクトのアウトラインを全てOFF
            else if (hit.collider.tag != "cube")
            {
                GameObject[] objects = GameObject.FindGameObjectsWithTag("cube");
                for (int i = 0; i < objects.Length; i++)
                {
                    objects[i].GetComponent<Outline>().enabled = false;
                };
            }
        }

        ///レイが当たっていなかったらcubeタグのアウトラインを全てOFF
        if (!Physics.Raycast(ray, out hit))
        {
            GameObject[] objects = GameObject.FindGameObjectsWithTag("cube");
            for (int i = 0; i < objects.Length; i++)
            {
                objects[i].GetComponent<Outline>().enabled = false;
            }
        }
    }
}

「補足」

もしrayの発車地点をマウスカーソルからVR用のコントローラーからなどからにするには

 public Transform rayTransform = null;


Ray laserPointer = new Ray(rayTransform.position, rayTransform.forward);

トランスフォームのところにRightHandAnchorを入れる。
Leghtでも良い。

 以上。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4