- Home /
How to activate a script from another script at runtime
Hi I need to know how to activate a script at runtime on a raycast collision heres the scripts im using now, the function update one is the one im using to find the gameobject and then find the script and then activate it on a raycast hit this one is called ZombieAIRaycast... And the one im trying to activate is the MoveForward script at the bottom. The move forward script is attached to my AI(ZombieCharacter) and the ZombieAIRaycast script is on my FirstPersonController(and no I did not get these mixed up) Please Help. The code I used is in Java.
function Update ()
{
var forward = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
Debug.DrawRay(transform.position, forward * 5, Color.blue);
if(Physics.Raycast(transform.position, forward, hit, 5))
{
if(hit.collider.gameObject.name == "top")
{
if(gameObject.Find("ZombieNormalDragLeg") != null)
{
Debug.Log("ZombieNromalDragLeg object found...");
gameObject.Find("ZombieNormalDragLeg").SendMessage("MoveForward");
}
}
}
}
Move Forward script
var speed : float = 5.0;
function Update () {
transform.Translate(Vector3(0,0,speed) * Time.deltaTime);
}
[Edit by Berenger, code formatting]
Answer by Berenger · May 06, 2012 at 10:54 PM
SendMessage is going to check if the gameobject has a function named MoveForward and then call it (several times if there is several component implementing it). So, you need to declare that function in the Move Forward script. You should use a different name to avoid confusion between the function and a constructor.
Note that the Find function is particularly slow, and you are using it twice. You should use FindWithTag instead, and store the result before checking if it was found.
Your answer
Follow this Question
Related Questions
Object won't reactivate or activate with button press. 2 Answers
Can somebody help me out with a jumpscare? (Like from the game "Slender") 1 Answer
Activate/Deactivate Script from another Object. 3 Answers
How to make movement on camera on button down. 1 Answer
How to instantiate gameobject on raycast collision. 1 Answer