Search code examples
c#classunity-game-engineunity-components

Unity3D Running A Script Inside Another Script


This has been driving me crazy and I have been at this with no luck for hours.

All I want to do is run one of my scripts from another script.

Both scripts are attached to the same game object. Here's the script I want to use to run the other script.

using UnityEngine;
using System.Collections;

public class RedTeam : MonoBehaviour {

public Wander wanderScript;

void Awake(){
    wanderScript = GetComponent<Wander>();
}

void Update(){ 
    wanderScript();
} 
}

Here is my wander script...

using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]

public class Wander : MonoBehaviour
{
public float speed = 5;
public float changeDirectionTime = 1;
public float maxDegreesToChange = 30;

CharacterController controller;
float heading;
Vector3 targetRotation;

void Awake ()
{
    controller = GetComponent<CharacterController>();

    // Set random rotation
    heading = Random.Range(0, 360);
    transform.eulerAngles = new Vector3(0, heading, 0);

    StartCoroutine(NewHeading());
}

void Update ()
{
    transform.eulerAngles = Vector3.Slerp(transform.eulerAngles, targetRotation, Time.deltaTime * changeDirectionTime);
    var forward = transform.TransformDirection(Vector3.forward);
    controller.SimpleMove(forward * speed);
}

IEnumerator NewHeading ()
{
    while (true) {
        NewHeadingRoutine();
        yield return new WaitForSeconds(changeDirectionTime);
    }
}

void NewHeadingRoutine ()
{
    var floor = Mathf.Clamp(heading - maxDegreesToChange, 0, 360);
    var ceil  = Mathf.Clamp(heading + maxDegreesToChange, 0, 360);
    heading = Random.Range(floor, ceil);
    targetRotation = new Vector3(0, heading, 0);
}
}

This is the error I am getting.

error CS1955: The member `RedTeam.wanderScript' cannot be used as method or delegate

My main goal is to be able to enable and disable the Wander script from my TeamRed script.


Solution

  • If you want to enable/disable the Wander script from your RedTeamScript, do the following in your RedTeamScript...

    wanderScript = GetComponent<Wander>();
    wanderScript.enabled = false;
    

    or

    wanderScript = GetComponent<Wander>();
    wanderScript.enabled = true;
    

    Note : GetComponent will only work because the Wander script is on the same gameObject. If the wander script was on another gameObject you would need to get a reference to that gameObject first and call GetComponent on it.

    It is also more efficient to declare

    wanderScript = GetComponent<Wander>();
    

    In your Start method so GetComponent is only called once.