How to add Component automatically.

1 minute read

Introduction

I will write a technical blog for the first time from today.

I will write what I learned even in small things.

Main subject

“shot” 2020-08-26 20.33.23.png

I put the cube like this.

Normally, I would press “Add Component” at the bottom right to add a component such as a rigid body, but I found a way to write a script that will do it automatically just by preparing a script.

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

public class Testscript : MonoBehaviour
{

    void Start()
    {
        
    }

    void Update()
    {
        
    }
}


I think it looks like this by default.
The name is “Testscript”.

Between the place where using ~ is written and the place where the class name is written

[RequireComponent(typeof(The name of the component you want to add))]

If you add this, the game object to which this script is attached will automatically add what is written in this “component you want to add” part.
For example, “Rigidbody”

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

[RequireComponent(typeof(Rigidbody))]

public class Testscript : MonoBehaviour
{

    void Start()
    {
        
    }

    void Update()
    {
        
    }
}

do this.

“shot” 2020-08-26 20.44.56.png

And when I attached this script to the cube, “Rigidbody” was automatically added.

If you get into the habit of writing this RequireComponent, you can reduce mistakes such as forgetting to attach a component, and you can save the trouble of manually adding it one by one!