GetComponent - Very Confused!

Hi, I have two scripts:

RunAndCrouch.js
CameraZoom.js

I’m trying to get it so that when i zoom on my camera - i slow down (i.e stop running).
In script terms, RunAndCrouch has this boolean:

var isRunning: boolean = false;

(when isRunning is true the character is running and when isRunning is false my character is not running)
and i would like it so that when i zoom my camera (in CameraZoom) while running (in RunAndCrouch), the boolean isRunning is set to false - meaning that i stop running. I’ve already watched youtube videos and read the unity docs but the whole ‘GetComponent’ thing is very confusing.
How would i go about using GetComponent to to this?
CameraZoom.js has these lines:

    var zoom : int = 20;
    var normal : int = 60;
    var smooth : float = 5;
    var isZoomed = false;
    var myAnimation : Animator;

    function Update () {
        var speed = walkSpeed;
        if(Input.GetKeyDown("q")){
            isZoomed = !isZoomed;
            }
            if(isZoomed == true){
                camera.fieldOfView = Mathf.Lerp(camera.fieldOfView,zoom,Time.deltaTime*smooth);
                myAnimation.SetBool("Sprint", false);
                }
            }
        if(Input.GetKeyUp("q")){
            isZoomed = isZoomed;
            }
    
            else{
                camera.fieldOfView = Mathf.Lerp(camera.fieldOfView,normal,Time.deltaTime*smooth);
            }
        }

Things to bear in mind:

  • I’ve already managed to get it so the Run animation bool is set to the walking animation when i zoom in.
    -The script RunAndCrouch.js is using a GetComponent from my Character Controller and Character Motor Script (will that affect it if trying to get a variable from a script that is getting a variable from another script?)
    -My CameraZoom script is attached to my Camera which is a child to my character - which is the object that my RunAndCrouch script is attached to.

Thanks
-Fin

GetComponent is used to get a component (script, rigidbody, meshrenderer etc.) on a gameobject of your choice. The type of component is always the name of the script you’re trying to access. If the component (script) you want to access is on the same object you’re calling from, using gameObject.GetComponent can be used to find the appropriate component. If the component you’re trying to access is on another gameobject, you first need to have an instance of that gameobject. You can get an instance by either making a public GameObject variable you can assign in the inspector, or you can find the gameobject manually by using GameObject targetObject = GameObject.Find(“NameOfObject”). Once you’ve found the correct gameobject, you can do something like this: targetObject.GetComponent(“NameOfScript”).nameOfVariable = value.

1 Like

Thank you! Very helpful!