How can I adjust the speed of an object through a seperate script?

Hello,

I have an assignment where I have to apply an enemy script (provided by my teacher) to an object, what this script does is tell the enemy where to walk and how fast to walk. I am tasked to slow down the enemy when it collides with a trigger but I can not modify the Enemy.cs script in any way.

Here is the script:

using UnityEngine;
using System.Collections;

// If you guys need any other function please let me know - Kevin
public class Enemy : MonoBehaviour 
{	
	private int health = 100;
	private float speed = 5f;
	public Transform[] path = null;
	private int pathIndex = 0;
	private float minDistance = 0.2f;
	private int damage = 1;
	public string targetTag = "";
		
	void Update () 
	{
		MoveInPath();
	}

	private void MoveInPath()
	{
		if (path.Length > pathIndex)	// "As long as the array is big enough..." - Avoids an index out of range exception
		{
			if (path[pathIndex] != null)	// "... and the current element exists"	- Avoids Null Reference exceptions
			{
				transform.position += (path[pathIndex].position - transform.position).normalized * speed * Time.deltaTime; // Move towards the current target
				if (Vector3.Distance(transform.position, path[pathIndex].position) < minDistance)	// "If I'm close enough to the target, select the next target"
				{
					pathIndex++;
				}
			}
		}
	}

	private void die()
	{
		Destroy(this.gameObject);
	}

	public void takeDamage(int damage)
	{
		health -= damage;
		if (health <= 0)
		{
			die();
		}
	}	
	
	public void setSpeed (float newSpeed)
	{
		speed = newSpeed;
	}
}

I’ve tried editing the speed variable in another script but it just doesn’t work, it seems as though that the speed variable doesn’t actually affect the speed at which the enemy walks.

Please leave your suggestions if you have any.

Thanks!

,

You’re probably mixing up things.

The speed variable itself is private. You can’t access it.

private float speed = 5f;

The person who wrote this script was providing a public function to modify the variable:

public void setSpeed (float newSpeed)

So, please use the setSpeed function. This is what the function is for.

You’ll have to get a reference to the gameobject the script is assigned to. (GetGameobject etc.)
Then get a reference to the script component of the gameobject. (GetComponent() etc.)
Then use the reference to call setSpeed.