How to Disable and Enable Scripts from Code

Boss entering the screen

Tristan Engel
Jul 25, 2021
Boss enter to center

In this article we start creating our enemy boss for our game. We start off with the boss entering our screen and staying at the middle.

For this we can just use the Vector3.MoveTowards function.

A separate script is used for this movement only so when the boss has reached the center we want to disable the script from code. The bold part disables the current script. With the same logic we can also enable other scripts to start the boss fight.

private float _speed = 2f;
private Vector3 _target = new Vector3(0, 1.5f, 0);

void Update()
{
transform.position = Vector3.MoveTowards(transform.position, _target, _speed * Time.deltaTime);
if (Vector3.Distance(transform.position, _target) < 0.001f)
{
this.GetComponent<BossMovementStart>().enabled = false;
}
}

--

--

Tristan Engel
Tristan Engel

Written by Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

No responses yet