Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

3rd person controller script(0 exp on coding and game dev)

Discussion in 'Scripting' started by seiketsuken, Aug 13, 2019 at 5:04 PM.

  1. seiketsuken

    seiketsuken

    Joined:
    Aug 2, 2019
    Posts:
    2
    Hey guys, I kinda need help on this. I'm following a tutorial on youtube by the name of @Sebastian Lague this is his script on the 3rd person controls:-

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Playercontroller : MonoBehaviour
    6. {
    7.     public float walkSpeed = 2;
    8.     public float runSpeed = 6;
    9.  
    10.     Animator animator;
    11.  
    12.  
    13.     // Start is called before the first frame update
    14.     void Start()
    15.     {
    16.         animator = GetComponent<Animator>();
    17.     }
    18.  
    19.     // Update is called once per frame
    20.     void Update()
    21.     {
    22.         Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    23.         Vector2 inputDir = input.normalized;
    24.  
    25.         if (inputDir != Vector2.zero)
    26.         {
    27.             transform.eulerAngles = Vector3.up * Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg;
    28.         }
    29.  
    30.         bool running = Input.GetKey(KeyCode.LeftShift);
    31.         float speed = ((running) ? runSpeed : walkSpeed) * inputDir.magnitude;
    32.  
    33.         transform.Translate(transform.forward * speed * Time.deltaTime, Space.World);
    34.  
    35.         float animationSpeedPercent = ((running) ? 1 : .5f) * inputDir.magnitude;
    36.         animator.SetFloat ("speedPercent", animationSpeedPercent);
    37.  
    38.         }
    39. }
    40.  
    so the problem is this line here :-
    Code (CSharp):
    1. animator.SetFloat ("speedPercent", animationSpeedPercent);
    2.  
    and unity shows this error : script.jpg

    Thanks for the help. :)
     
  2. DryerLint

    DryerLint

    Joined:
    Feb 7, 2016
    Posts:
    44
    The problem is animator is not instantiated (with the new keyword), nor assigned to any pre-existing instance (have a look at the topic of instantiation in C#).

    In Start(), GetComponent<Animator>() is called to find an instance of Animator as a component in the GameObject your script is attached to, and fails. You probably forgot to add an Animator component in the Inspector.

    I hope all of that made sense. Good luck!
     
  3. seiketsuken

    seiketsuken

    Joined:
    Aug 2, 2019
    Posts:
    2
    that probably make sense. thanks fellow dev.!