LoginSignup
0
0

More than 3 years have passed since last update.

【Unity】他のゲームオブジェクトの子オブジェクトをスクリプトで操作する方法

Last updated at Posted at 2020-10-08

ezgif.com-gif-maker.gif

今回はゲームオブジェクトから他のゲームオブジェクトの子オブジェクトの色を変えてみる。

“shot” 2020-10-09 1.06.22.png

最初に空のゲームオブジェクトを作る。
キューブを作り、さらにその下にキューブをつける。
名前は「cube1」とした。

スクリプトを書く。
今回はインスペクターで指定したオブジェクトの子オブジェクトのRendererにアクセスする。

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

public class TestScript : MonoBehaviour
{

    public GameObject obj;

    Renderer renderercolor;

    void Start()
    {
        renderercolor = obj.transform.Find("cube1").gameObject.GetComponent<Renderer>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            renderercolor.material.color = new Color(1f, 0.0f, 0.0f, 0.0f);

        }
    }
}
renderercolor = obj.transform.Find("cube1").gameObject.GetComponent<Renderer>();

ここの部分でpublicで指定したゲームオブジェクトの子オブジェクトを見つけてRendererをGetComponentし、変数に入れる。Find("")のカッコの中にはアクセスする子オブジェクトの名前を入れる。

できたら空のゲームオブジェクトにつける。

“shot” 2020-10-09 1.07.23.png

再生し、クリックすると赤色になる。
キューブにマテリアルをつけるのを忘れずに!

0
0
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
0
0