Search Unity

Question Awake not working (I think?)

Discussion in 'Scripting' started by jb11292007, May 9, 2023.

  1. jb11292007

    jb11292007

    Joined:
    Apr 8, 2022
    Posts:
    4
    So I needed character movement and animation so i watched a YouTube tutorial (
    ) after finished following the steps I pressed play i got a bunch of errors saying missing hash and i couldn't move my character because the input manager script wasn't enable so i enabled it in game i tried walking around and I found out that when i let go of the wasd keys my character doesn't stop moving in game so i check the code and I'm pretty sure it has to do with awake since the script disables its self after pressing play or am i being stupid sorry for the weird grammar and noob behavior
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Post code in the forums using code tags. :)

    Did you add Debug.log calls in your scripts to see what methods are running? Note that Awake requires an active gameobject for it to run. Also, if you are getting errors, those errors can stop your code from completely running, which may keep things from behaving correctly. Make sure you address those errors as well.
     
    Bunny83 likes this.
  3. jb11292007

    jb11292007

    Joined:
    Apr 8, 2022
    Posts:
    4
    so sorry about the tags also Im new to using unity and code overall not sure what debug.logs are BUT i did get all the errors fixed so that wasnt the problem and the active game object I'm also kinda confused and still learning about sorry for being oblivious to this stuff
     
  4. jb11292007

    jb11292007

    Joined:
    Apr 8, 2022
    Posts:
    4
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityTutorial.Manager;
    6.  
    7. namespace UnityTutorial.PlayerControl
    8. {
    9.     public class PlayerController : MonoBehaviour
    10.     {
    11.         [SerializeField] private float AnimBlendSpeed = 8.9f;
    12.         [SerializeField] private Transform CameraRoot;
    13.         [SerializeField] private Transform Camera;
    14.         [SerializeField] private float UpperLimit = -40f;
    15.         [SerializeField] private float BottomLimit = 70f;
    16.         [SerializeField] private float MouseSensitivity = 21.9f;
    17.         [SerializeField, Range(10, 500)] private float JumpFactor = 260f;
    18.         [SerializeField] private float Dis2Ground = 0.8f;
    19.         [SerializeField] private LayerMask GroundCheck;
    20.         [SerializeField] private float AirResistance = 0.8f;
    21.         private Rigidbody _playerRigidbody;
    22.         private InputManager _inputManager;
    23.         private Animator _animator;
    24.         private bool _grounded = false;
    25.         private bool _hasAnimator;
    26.         private int _xVelHash;
    27.         private int _yVelHash;
    28.         private int _jumpHash;
    29.         private int _groundHash;
    30.         private int _fallingHash;
    31.         private int _zVelHash;
    32.         private int _crouchHash;
    33.         private float _xRotation;
    34.  
    35.         private const float _walkSpeed = 2f;
    36.         private const float _runSpeed = 6f;
    37.         private Vector2 _currentVelocity;
    38.      
    39.  
    40.  
    41.         private void Start() {
    42.             _hasAnimator = TryGetComponent<Animator>(out _animator);
    43.             _playerRigidbody = GetComponent<Rigidbody>();
    44.             _inputManager = GetComponent<InputManager>();
    45.  
    46.  
    47.             _xVelHash = Animator.StringToHash("X_Velocity");
    48.             _yVelHash = Animator.StringToHash("Y_Velocity");
    49.             _zVelHash = Animator.StringToHash("Z_Velocity");
    50.             _jumpHash = Animator.StringToHash("Jump");
    51.             _groundHash = Animator.StringToHash("Grounded");
    52.             _fallingHash = Animator.StringToHash("Falling");
    53.             _crouchHash = Animator.StringToHash("Crouch");
    54.         }
    55.  
    56.         private void FixedUpdate() {
    57.             SampleGround();
    58.             Move();
    59.             HandleJump();
    60.             HandleCrouch();
    61.         }
    62.         private void LateUpdate() {
    63.             CamMovements();
    64.         }
    65.  
    66.         private void Move()
    67.         {
    68.             if(!_hasAnimator) return;
    69.  
    70.             float targetSpeed = _inputManager.Run ? _runSpeed : _walkSpeed;
    71.             if(_inputManager.Crouch) targetSpeed = 1.5f;
    72.             if(_inputManager.Move ==Vector2.zero) targetSpeed = 0;
    73.  
    74.             if(_grounded)
    75.             {
    76.              
    77.             _currentVelocity.x = Mathf.Lerp(_currentVelocity.x, _inputManager.Move.x * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);
    78.             _currentVelocity.y =  Mathf.Lerp(_currentVelocity.y, _inputManager.Move.y * targetSpeed, AnimBlendSpeed * Time.fixedDeltaTime);
    79.  
    80.             var xVelDifference = _currentVelocity.x - _playerRigidbody.velocity.x;
    81.             var zVelDifference = _currentVelocity.y - _playerRigidbody.velocity.z;
    82.  
    83.             _playerRigidbody.AddForce(transform.TransformVector(new Vector3(xVelDifference, 0 , zVelDifference)), ForceMode.VelocityChange);
    84.             }
    85.             else
    86.             {
    87.                 _playerRigidbody.AddForce(transform.TransformVector(new Vector3(_currentVelocity.x * AirResistance,0,_currentVelocity.y * AirResistance)), ForceMode.VelocityChange);
    88.             }
    89.  
    90.  
    91.             _animator.SetFloat(_xVelHash , _currentVelocity.x);
    92.             _animator.SetFloat(_yVelHash, _currentVelocity.y);
    93.         }
    94.  
    95.         private void CamMovements()
    96.         {
    97.             if(!_hasAnimator) return;
    98.  
    99.             var Mouse_X = _inputManager.Look.x;
    100.             var Mouse_Y = _inputManager.Look.y;
    101.             Camera.position = CameraRoot.position;
    102.          
    103.          
    104.             _xRotation -= Mouse_Y * MouseSensitivity * Time.smoothDeltaTime;
    105.             _xRotation = Mathf.Clamp(_xRotation, UpperLimit, BottomLimit);
    106.  
    107.             Camera.localRotation = Quaternion.Euler(_xRotation, 0 , 0);
    108.             _playerRigidbody.MoveRotation(_playerRigidbody.rotation * Quaternion.Euler(0, Mouse_X * MouseSensitivity * Time.smoothDeltaTime, 0));
    109.         }
    110.  
    111.         private void HandleCrouch() => _animator.SetBool(_crouchHash , _inputManager.Crouch);
    112.  
    113.  
    114.         private void HandleJump()
    115.         {
    116.             if(!_hasAnimator) return;
    117.             if(!_inputManager.Jump) return;
    118.             if(!_grounded) return;
    119.             _animator.SetTrigger(_jumpHash);
    120.  
    121.             //Enable this if you want B-Hop
    122.             //_playerRigidbody.AddForce(-_playerRigidbody.velocity.y * Vector3.up, ForceMode.VelocityChange);
    123.             //_playerRigidbody.AddForce(Vector3.up * JumpFactor, ForceMode.Impulse);
    124.             //_animator.ResetTrigger(_jumpHash);
    125.         }
    126.  
    127.         public void JumpAddForce()
    128.         {
    129.             //Comment this out if you want B-Hop, otherwise the player will jump twice in the air
    130.             _playerRigidbody.AddForce(-_playerRigidbody.velocity.y * Vector3.up, ForceMode.VelocityChange);
    131.             _playerRigidbody.AddForce(Vector3.up * JumpFactor, ForceMode.Impulse);
    132.             _animator.ResetTrigger(_jumpHash);
    133.         }
    134.  
    135.         private void SampleGround()
    136.         {
    137.             if(!_hasAnimator) return;
    138.          
    139.             RaycastHit hitInfo;
    140.             if(Physics.Raycast(_playerRigidbody.worldCenterOfMass, Vector3.down, out hitInfo, Dis2Ground + 0.1f, GroundCheck))
    141.             {
    142.                 //Grounded
    143.                 _grounded = true;
    144.                 SetAnimationGrounding();
    145.                 return;
    146.             }
    147.             //Falling
    148.             _grounded = false;
    149.             _animator.SetFloat(_zVelHash, _playerRigidbody.velocity.y);
    150.             SetAnimationGrounding();
    151.             return;
    152.         }
    153.  
    154.         private void SetAnimationGrounding()
    155.         {
    156.             _animator.SetBool(_fallingHash, !_grounded);
    157.             _animator.SetBool(_groundHash, _grounded);
    158.         }
    159.     }
    160. }
    161.  
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityEngine.InputSystem;
    4. using UnityEngine.InputSystem.Interactions;
    5.  
    6. namespace UnityTutorial.Manager
    7. {
    8.     public class InputManager : MonoBehaviour
    9.     {
    10.         [SerializeField] private PlayerInput PlayerInput;
    11.  
    12.         public Vector2 Move {get; private set;}
    13.         public Vector2 Look {get; private set;}
    14.         public bool Run {get; private set;}
    15.         public bool Jump {get; private set;}
    16.         public bool Crouch {get; private set;}
    17.  
    18.         private InputActionMap _currentMap;
    19.         private InputAction _moveAction;
    20.         private InputAction _lookAction;
    21.         private InputAction _runAction;
    22.         private InputAction _jumpAction;
    23.         private InputAction _crouchAction;
    24.  
    25.         private void Awake() {
    26.             HideCursor();
    27.             _currentMap = PlayerInput.currentActionMap;
    28.             _moveAction = _currentMap.FindAction("Move");
    29.             _lookAction = _currentMap.FindAction("Look");
    30.             _runAction  = _currentMap.FindAction("Run");
    31.             _jumpAction = _currentMap.FindAction("Jump");
    32.             _crouchAction = _currentMap.FindAction("Crouch");
    33.  
    34.             _moveAction.performed += onMove;
    35.             _lookAction.performed += onLook;
    36.             _runAction.performed += onRun;
    37.             _jumpAction.performed += onJump;
    38.             _crouchAction.started += onCrouch;
    39.  
    40.             _moveAction.canceled += onMove;
    41.             _lookAction.canceled += onLook;
    42.             _runAction.canceled += onRun;
    43.             _jumpAction.canceled += onJump;
    44.             _crouchAction.canceled += onCrouch;
    45.         }
    46.  
    47.         private void HideCursor()
    48.         {
    49.             Cursor.visible = false;
    50.             Cursor.lockState = CursorLockMode.Locked;
    51.         }
    52.  
    53.         private void onMove(InputAction.CallbackContext context)
    54.         {
    55.             Move = context.ReadValue<Vector2>();
    56.         }
    57.         private void onLook(InputAction.CallbackContext context)
    58.         {
    59.             Look = context.ReadValue<Vector2>();
    60.         }
    61.         private void onRun(InputAction.CallbackContext context)
    62.         {
    63.             Run = context.ReadValueAsButton();
    64.         }
    65.         private void onJump(InputAction.CallbackContext context)
    66.         {
    67.             Jump = context.ReadValueAsButton();
    68.         }
    69.         private void onCrouch(InputAction.CallbackContext context)
    70.         {
    71.             Crouch = context.ReadValueAsButton();
    72.         }
    73.  
    74.         private void OnEnable() {
    75.             _currentMap.Enable();
    76.         }
    77.  
    78.         private void OnDisable() {
    79.             _currentMap.Disable();
    80.         }
    81.      
    82.     }
    83. }
    84.  
    Thats The code
     
  5. mopthrow

    mopthrow

    Joined:
    May 8, 2020
    Posts:
    348
    In Unity Debug.Log() prints a message to your console. It's useful to check if a piece of code runs and to print information about your script to see if the values are what you expect them to be. It's critical for debugging and will help you solve most of your errors.

    Few examples:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Debugs : MonoBehaviour
    4. {
    5.     public int someValue = 10;
    6.     public float someOtherValue = 5.2f;
    7.     public string alsoSomething = "hello";
    8.  
    9.     void Start()
    10.     {
    11.         Debug.Log("Your Message");
    12.         Debug.Log("GameObjectName: " + gameObject.name);
    13.         Debug.Log("My number: " + 5.2f);
    14.         Debug.Log("Also my number: " + someOtherValue);
    15.         Debug.Log("First thing: " + someValue + ", second thing: " + someOtherValue + ", last thing: " + alsoSomething + ".");
    16.         Debug.Log($"First thing: {someValue}, second thing: {someOtherValue}, lastThing: {alsoSomething}.");
    17.     }
    18. }
    More in Unity Scripting Reference: https://docs.unity3d.com/ScriptReference/Debug.Log.html

    Would highly recommend the Junior Programmer pathway. I hear it's great if you're just starting out in Unity is likely to speed your progress a lot. https://learn.unity.com/pathway/junior-programmer
     
    jb11292007, Bunny83 and spiney199 like this.
  6. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,008
    Well, "scripts" in Unity (more specifically classes derived from MonoBehaviour) are custom components. They need to be attached to a GameObject in the scene. Unity's component system allows you to create gameobjects in your world which are just empty shells / mediators and act as a socket for components. Components essentially define what that object actually does and how it behaves. An object needs some kind of Renderer in order to show up in the world. There are other components like the Rigidbody component which turns the object into a physics controlled object.

    Besides the built-in components there are also our own MonoBehaviour scripts which you can attach to an object to give that object "behaviour". It's called MonoBehaviour because we write our behaviours with C# on the managed "Mono" side. Mono is just an open source and cross platform variant of the .NET framework.

    So in order for a MonoBehaviour script to do anything, it needs to be attached to an "active" gameobject in the scene. GameObjects can be deactivated in which case they still exist, but don't do anything. Certain components can also individually be enabled / disabled. To attach a script to a gameobject you just need to drag the script onto the gameobject. You will see the instance in the inspector when you select the gameobject. You can also add components at runtime from code by using AddComponent if necessary. Though it's common to create predesigned prefabs which you then instantiate into the scene.

    So when you add a Debug.Log statement to your Awake method, you will immediately see in the console when you run your game if Awake runs or not.

    Note: You can also pass a "context" object to Debug.Log as second argument. This can be any gameobject, component or other engine object. When you then click on the log message in the console, the editor will highlight / "ping" that object in the hierarchy or project view. This can help identifying the actual object you're dealing with.
     
    Brathnann and Yoreki like this.
  7. jb11292007

    jb11292007

    Joined:
    Apr 8, 2022
    Posts:
    4
    alright so I can confirm that the awake function is indeed working through using debug.log and it is attached to a game object but it seems that the . cancel functions aren't working properly and still have absolutely no idea why